javascript Expressjs 安全会话 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8455272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:30:20  来源:igfitidea点击:

Expressjs secure session cookie

javascriptnode.jsexpress

提问by georgesamper

I cant seem to find a way to set a secure cookie in expressjs framework. Is there an option to do this somewhere?

我似乎找不到在 expressjs 框架中设置安全 cookie 的方法。是否可以选择在某处执行此操作?

回答by dgreisen

If you are behind a proxy, you also have to ensure it is sending the X-Forwarded-Protoheader and that you set the proxy option:

如果您在代理后面,您还必须确保它正在发送X-Forwarded-Proto标头并设置代理选项:

app.use(express.session({
  proxy: true,
  secret: 'test',
  cookie: {
    secure: true
  }            
}));

Alternatively, you can tell Express to trust the proxy globally:

或者,您可以告诉 Express 全局信任代理:

app.set('trust proxy', 1)

回答by dchrastil

Based on the documentation, try this:

根据文档,试试这个:

res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true, secure: true });

Using res.cookie(name, val[, options])sets the given cookie name to val, with options httpOnly, secure, expires, etc. The pathoption defaults to the app's basepathsetting, which is typically "/".

使用res.cookie(name, val[, options])将给定的 cookie 名称设置为val,以及选项httpOnlysecureexpires等。该path选项默认为应用程序的basepath设置,通常为"/"

See the docs for res.cookiefor more details.

有关更多详细信息,请参阅文档res.cookie