![](/img/trans.png)
[英]I can't set the SameSite attribute of the cookie to None in Nodejs (Express)
[英]Why do I keep getting a warning: A cookie associated with a resource at http://127.0.0.1/ was set with `SameSite=None` but without `Secure`
完整的警告信息:
A cookie associated with a resource at http://127.0.0.1/ was set with `SameSite=None` but without `Secure`. A future release of Chrome will only deliver cookies marked `SameSite=None` if they are also marked `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5633521622188032.
但是,我将 cookies 设置为:
res.cookie("token", token, {httpOnly: true, sameSite: 'none', secure: true});
有没有办法摆脱这个警告?
对于第三方或跨站点上下文中所需的 cookie,您应该设置SameSite=None
和Secure
,就像您在原始示例中所做的那样。
第一个问题 - 你肯定需要这个 cookie 是跨站点的吗? 换句话说,您是否期望不同的站点向您的站点发出需要发送此 cookie 的请求? 此处的示例是,如果您的站点嵌入在另一个站点的 iframe 中,托管您希望包含 cookies 的图像,或者创建一个令牌以提高跨站点表单提交的安全性。
如果不是,请考虑SameSite=Lax
代替此 cookie。 这样,它将仅针对您站点内的请求发送。
但是,当您在127.0.0.1
或localhost
上进行开发时,您通常没有有效 HTTPS 连接的证书。 我建议在 Express 中使用app.get('env);
获取您当前的环境( 'development'
或'production'
),然后使用它来选择是否设置Secure
。
例如:
const express = require('express');
const app = express();
if (app.get('env') !== 'development') {
// production settings, assume HTTPS
app.set('cookie config', { httpOnly: true, sameSite: 'lax', secure: true });
} else {
// development settings, no HTTPS
app.set('cookie config', { httpOnly: true, sameSite: 'lax' });
}
// Later on when setting a cookie within your route, middleware, etc.
res.cookie('token', token, app.get('cookie config'));
如果您的站点上有不同的用例,您还可以设置多个 cookie 配置。
if (app.get('env') !== 'development') {
// production settings, assume HTTPS
app.set('cookie config 1p', { httpOnly: true, sameSite: 'lax', secure: true });
app.set('cookie config 3p', { httpOnly: true, sameSite: 'none', secure: true });
} else {
// development settings, no HTTPS
app.set('cookie config 1p', { httpOnly: true, sameSite: 'lax' });
// Assumes that I'm hosting all my test sites under localhost,
// so the browser won't actually see them as 3p
app.set('cookie config 3p', { httpOnly: true, sameSite: 'lax' });
}
您还可以查找为您的 localhost 环境创建自签名证书,但这可能有点麻烦。 如果您打算这样做,则最好将精力放在使用某种容器或虚拟机进行开发上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.