Passport 的注销功能会删除 cookie 吗?如果没有,它是如何工作的?

Does Passport's logout function remove the cookie? If not, how does it work?

来自docs

Passport exposes a logout() function on req (also aliased as logOut()) that can be called from any route handler which needs to terminate a login session. Invoking logout() will remove the req.user property and clear the login session (if any).

app.get('/logout', function(req, res){   req.logout();  
res.redirect('/'); });

从阅读本文和测试我自己来看,logout 似乎没有从客户端删除 cookie。据我了解,当客户端发出请求时,它会发送它的 cookie,Passport 将其反序列化并转换为 req.user.

假设logout不删除cookie,Passport使用cookie来判断用户是否登录,那么logout函数是如何实现的 实际上注销用户?

据我所知这是常见问题。您可以尝试以下方法。

  1. 尝试使用 logOut() 而不是 logout()

    req.logOut(); req.redirect('\');

  2. 尝试使用session.destroy

    req.session.destroy(function (err) { res.redirect('/'); });

您还可以参考link: https://github.com/jaredhanson/passport/issues/216

不,不是。 passport.js 中的 req.logout 方法,IMO,真的很糟糕。它所做的只是从 req 对象中删除 'user' 属性 。它不会触及任何 cookie 或更新您的会话存储中的会话信息。

你必须手动完成另外两件事,即

//first remove the "passport" key from the session in your store
//or set it to null
//then, when you get the confirmation callback from your store...

    res.clearCookie('sid', {path: '/'});
    res.redirect('/');

这是完整的解决方案,将从服务器删除整个会话并清除客户端的 cookie

module.exports.getLogout = function (req, res, next) {
    req.logout();
    req.session.destroy(function (err) {
        if (!err) {
            res.status(200).clearCookie('connect.sid', {path: '/'}).json({status: "Success"});
        } else {
            // handle error case...
        }

    });
};

好吧,您不需要从客户端删除 cookie,因为一旦您调用 req.logout() 函数(由 passport 公开),passport 就会删除代表 req.user 的对象服务器上的身份验证状态。

在客户端,cookie本身并没有被销毁,而是被作废了。您可以在点击注销按钮(执行 req.logout)之前和之后检查 cookie。您将看到 cookie 已更改,包括其字符串表示形式和大小。

在您注销后,cookie 的大小将减小到基本大小,因为已设置的有关用户的所有数据都已被销毁。或者换句话说,cookie是没用的。

大约四年后我遇到了这个问题,幸运的是,我想我现在明白了。

Passport 的 logout 函数 不会 为您清除会话 ID cookie。然而,这实际上不是问题。我会解释为什么。

登录后,工作原理如下。当您向服务器发送请求时,会话 ID cookie 会随请求一起发送。然后服务器获取该会话 ID,查找具有活动会话的相应用户,并为您填充 req.user

话虽如此,请考虑一下如果您注销但不要清除该会话 ID cookie 会发生什么。下次发送请求时,cookie 仍将一起发送,因为它没有被清除。但接下来会发生什么?它会尝试查找具有活动会话的相应用户......但它不会找到任何东西!所以 req.user 最终不会被填充。这就是为什么该 cookie 是否被删除并不是什么大问题。