【问题标题】:Express cookie-session not saving cookie when SameSite is set to 'none' and secure is set to true当 SameSite 设置为“无”且安全设置为 true 时,Express cookie-session 不保存 cookie
【发布时间】:2021-09-05 10:57:42
【问题描述】:

我正在使用 cookie-session 和 passportjs 对我的 express 应用中的用户进行身份验证。当我像这样初始化我的 cookieSession 时:

app.use(cookieSession({
    maxAge: 24 * 60 * 60 * 1000,
    keys: ['key1']
}));

我的 cookie 已成功保存到客户端。但是,我正在进行的项目需要跨站点请求。因此,cookie 的安全属性必须设置为 true,并且 SameSite 属性必须设置为 none。在文档中,这些值可以设置如下:

app.use(cookieSession({
    maxAge: 24 * 60 * 60 * 1000,
    secure: true,
    sameSite: 'none',
    keys: ['key1']
}));

但是,当我这样做时,cookie 无法保存到客户端。我想知道是否有人知道如何解决此问题或为什么会发生这种情况?

提前谢谢你。

【问题讨论】:

    标签: express cookies passport.js samesite cookie-session


    【解决方案1】:

    answer by Luka Darsalia 告诉我,至少在我的情况下,服务器拒绝向客户端发送 secure:true cookie,因为它认为客户端不安全(因为 request.protocol 是 http 而不是比https)。

    起初我对此感到困惑,因为我的地址栏显示https。但后来我想起https只是用于我的浏览器和Cloudflare CDN之间的连接——Cloudflare CDN和我的实际服务器之间的连接仍然使用http。

    因此,要修复它,我只需要确保 cookie-session(更具体地说,cookies 包中的 this line)连接是安全的,然后继续使用 @987654332 发送 cookie @标志。

    为此,我只是在cookieSession 中间件之后添加了以下中间件:

    // your existing cookieSession init here
    app.use(cookieSession({
        [...]
        secure: true,
        sameSite: "none",
    }));
    
    // enable the "secure" flag on the sessionCookies object
    app.use((req, res, next)=>{
        req["sessionCookies"].secure = true;
        next();
    });
    

    【讨论】:

    • 这看起来就像我需要的一样,因为我们的问题是相同的,正如你所说的那样。但是在我在“//启用“安全”下添加行之后......我在服务器上收到了这个错误消息:“err.message:无法设置未定义的属性'安全'”有什么想法吗?谢谢。
    • 我会使用开发工具或日志检查“req”变量,并尝试在该对象上找到保存 cookie 数据的属性。如果它不存在,那么您正在使用的 cookie-session 库(或者您正在使用不同的库?)可能没有正确设置。
    • 我想知道我是否没有定义一个值。在上面的第一个中间件代码中,您使用 cookieSession,然后在下一个中间件代码中,您使用 sessionCookies。那是故意的还是错过的?如果是故意的,sessionCookies 是在哪里定义的?
    • 已经有一段时间了,但我相信我是从我的工作代码中复制粘贴的,所以这是故意的。我记得 sessionCookies 属性是由 cookieSession 中间件设置的。
    【解决方案2】:

    认证后使用这个:

    passport.authenticate("local");
       req.session.save((error) => {
         if (err) {
           console.log(err);
         } else {
           res.redirect("/");
          }
    });
    

    【讨论】:

    • 虽然这并没有解决我的问题(遇到与 OP 相同的问题),但它确实揭示了问题:它导致页面显示错误 Error: Cannot send secure cookie over unencrypted connection。
    猜你喜欢
    • 2020-01-05
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2017-06-20
    • 2020-05-17
    • 2021-11-18
    • 2020-11-01
    相关资源
    最近更新 更多