Node JS,express-session,从客户端浏览器中删除cookie

4

我正在处理一个已经有自己基础设施的应用程序,任务是防止用户在多个浏览器中登录。我们的应用程序具有单一应用程序架构,因此理想情况下,用户只应在一个浏览器选项卡中工作。但是我有一个问题。我无法从客户端删除cookie。

I. 简要说明。

应用程序设置:

服务器:NodeJS 端口:8083

客户端:VueJS 端口:8088

我使用模块express-session在服务器端初始化会话机制并将cookie发送到客户端。客户端没有设置cookie。

II. 详细信息:

服务器的根文件是index.js

我在其中执行以下操作:

  1. 插入express模块:
const express = require('express')
  1. 安装 cors 模块:
const cors = require('cors')
  1. 添加 cors 设置:
app.use(cors({
    origin: 'http://localhost:8088',
    credentials: true
}))

我将为您翻译以下内容:

然后,我在 user.js 文件中初始化会话,并接收客户端的连接:

  1. 插入 express-session 模块:
const session = require('express-session')
  1. 通过 express.Router() 插入路由:
const router = express.Router()
  1. 添加会话设置:
const EIGHT_HOURS  = 1000 * 60 * 60 * 8
const {
    SESS_NAME = 'sid',
    SESS_LIFETIME = EIGHT_HOURS,
    SESS_SECRET = 'test',
    NODE_ENV = 'development'
} = process.env
const IN_PROD = NODE_ENV === 'production'
  1. 初始化会话:
router.use(session({
    name: SESS_NAME,
    resave: false,
    saveUninitialized: false,
    secret: SESS_SECRET,
    cookie: {
        maxAge: SESS_LIFETIME,
        sameSite: false,
        // Must have HTTPS to work 'secret:true'
        secure: IN_PROD
    }
}))
  1. 通过router.post()接收客户端查询。

所以我做了以下事情:

  1. 我使用req.session.destroy来删除会话数据,并期望浏览器注销用户并清除某些浏览器和cookie。
req.session.destroy(err => {
            if (err) {
                return res.send({ error: 'Logout error' })
            }
            res.clearCookie(SESS_NAME, {path: '/'})
            return res.send({ 'clearSession': 'success' })
        })

很遗憾,没有任何魔法会发生。

  1. 我阅读了不同的主题。例如,在这里(GitHub)提供结论:在res.clearCookie方法中使用显式cookie路径指示,如上所示。但那并没有起作用。

  2. 在cookie设置中编写此设置{path: '/'}。也没用。

router.use(session({
    name: SESS_NAME,
    resave: false,
    saveUninitialized: false,
    secret: SESS_SECRET,
    cookie: {
    path: '/',
        maxAge: SESS_LIFETIME,
        sameSite: false,
        // Must have HTTPS to work 'secret:true'
        secure: IN_PROD
    }
}))

正如NPM:express-session文档中所写,此路径是cookie存储的默认路径。

  1. 在req.session.destroy中添加req.session = null
req.session.destroy(err => {
            if (err) {
                return res.send({ error: 'Logout error' })
            }
            req.session = null
            res.clearCookie(SESS_NAME, {path: '/'})
            return res.send({ 'clearSession': 'success' })
        })

那个没用。

  1. delete req.session 也不管用。

那么,我该怎么解决这个问题?我该做什么?

5个回答

4

在我的浏览器中添加.send('cleared cookie')会使得它清除命名cookie的缓存。

const logOutRequest = (req, res) => {
      req.session.destroy((err) => {
         res.clearCookie("notcookie").send('cleared cookie');
      });
    };

0
最重要的关键是在 clearCookie 方法中设置“domain”来解决您的问题。 Expressjs 将在 HTTP 响应头中返回以下内容。但是,似乎在浏览器或某些我测试过的浏览器上,它不知道清除哪个属于哪个域的 cookie,因此该 cookie 仍然存在。在调用 clearCookie 时不需要包含路径。
Set-Cookie: mycookie=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT

你需要像下面这样设置域名:

 req.session.destroy(err => {
        res.clearCookie("session-cookie-name", { domain: 'your-domain' });
    });

那么响应头将变为

Set-Cookie: mycookie=; Domain=your-domain; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT

浏览器会很好地清除Cookie!


0

这对我有效

@Post('signout')
async signout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
  const user = req.user

  if (!user) return {}

  await new Promise<void>((resolve, reject) => {
    req.session.destroy((err) => {
      if (err) {
        reject(err)
      } else {
        res.clearCookie('ACCESS_TOKEN', {
          domain: '.xxx.com'
        })
        res.clearCookie('REFRESH_TOKEN', {
          domain: '.xxx.com'
        })
        res.clearCookie('connect.sid', {
          domain: '.xxx.com'
        })

        resolve()
      }
    })
  })

  return {}
}

0

这将从客户端浏览器中删除cookie

req.session.destroy(err => {
    res.clearCookie("session-cookie-name", { path: "/" });
  });

0

你尝试过通过将确切的cookie设置为null来删除它吗?比如说,如果你正在处理一个名为Views的cookie,你可以使用req.session.Views = null来删除该cookie。

与其这样做,

req.session.destroy(err => {
            if (err) {
                return res.send({ error: 'Logout error' })
            }
            req.session = null
            res.clearCookie(SESS_NAME, {path: '/'})
            return res.send({ 'clearSession': 'success' })
        })

你可以将会话 cookie 的名称设置为 null。

req.session.sid= null

哦,请问您能具体说明一下我应该在哪里写这个 req.session.Views = null 代码行吗?当您说 Views 时,是指会话设置中的 name: SESS_NAME 这样的东西吗?也就是说,我需要写 req.session.SESS_NAME = null 吗? - Gleb Tregubov
很遗憾,它不起作用。会话没有清除。行req.session.SESS_NAME = null只是在会话存储中添加了新字段。它看起来像这样:Session { cookie: { path: '/', _expires: 2019-10-10T21:08:28.940Z, originalMaxAge: 28800000, httpOnly: true, secure: false, sameSite: false }, userId: 1, blocked: 0, status: 'lambda', SESS_NAME: null } - Gleb Tregubov
抱歉,我看到你的会话名称是“sid”,请将其设置为null,即req.session.sid = null。 - user11720628
再次不幸的是,在req.session.sid = null行中明确添加了SESS_NAME,结果与之前相同。只有会话存储中的新行:Session { cookie: { path: '/', _expires: 2019-10-10T21:38:26.600Z, originalMaxAge: 28800000, httpOnly: true, secure: false, sameSite: false }, userId: 489, login: 'glebtregubov', password: '10293221', blocked: 0, status: '392', sid: null } - Gleb Tregubov
你正在使用最新版本的express-session吗? - user11720628
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接