简体   繁体   English

如何设置会话cookie以保护和使用CSRF令牌?

[英]How do I set a session cookie to secure and use CSRF tokens?

I have an express application where I am trying to set the session cookie to secure. 我有一个快速应用程序,试图将会话cookie设置为安全。 So far I have tried the code below: 到目前为止,我已经尝试了以下代码:

app.use(express.cookieParser());
sessionOptions = definitions.REDIS;
sessionOptions.ttl = definitions.session.expiration;
app.use(express.session({
  secret: definitions.session.secret,
  cookie: {                 <---------------------------- Added this
    secure: true
  },
  store: new RedisStore(sessionOptions)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.bodyParser());
app.use(express.csrf());
app.use(function(req, res, next) {
  res.locals.token = req.session._csrf;
  return next();
});

But now when I try to log in the CSRF token does not validate and I get a forbidden error. 但是现在当我尝试登录CSRF令牌时,它无法验证,并且我收到了一个禁止的错误。 How can I make the session cookie secure AND use a CSRF token? 如何使会话cookie安全并使用CSRF令牌?

Here's what I use. 这是我用的。 I don't think you need the return before next() , but I'm not sure if that's your issue. 我认为您不需要在next()之前return ,但是我不确定这是否是您的问题。

app
.set('view engine', 'jade')
.set('views', __dirname + '/../views')
.set('json spaces', 2)
.use(express.compress())
.use(express.cookieParser('our secret'))
.use(express.session({
  store: new RedisStore({
    port: config.redisPort,
    host: config.redisHost,
    db: config.redisDatabase,
    pass: config.redisPassword
  }),
  proxy: true,
  cookie: { httpOnly: true, secure: true }
}))
.use(express.bodyParser())
.use(express.methodOverride())
.use(express.csrf())
.use(function (req, res, next) {
  res.cookie('XSRF-TOKEN', req.csrfToken());
  res.locals.csrftoken = req.csrfToken();
  next();
})
.use(everyauth.middleware());

The proxy: true is necessary for Heroku. proxy: true对于Heroku是必需的。 Note that req.session._csrf has been obsoleted in the latest version of Express. 请注意,最新版本的Express已淘汰了req.session._csrf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM