如何使用Angular和Node Express将CSRF与Redis Session配合使用,会话过期后如何重置会话信息和CSRF?

我正在运行Express和NodeJS作为angular度前端的后端。 我正在使用RedisStore进行会话。 使用这个博客文章 ,我能够拿出以下代码:

app.use express.cookieParser(config.session.signed) app.use express.session( { secret: config.session.secret, cookie: config.session.cookie, store: new RedisStore({ client: client }) } ) app.use express.csrf() app.use (req, res, next) -> res.cookie('XSRF-TOKEN', req.session._csrf) next() app.use passport.initialize() app.use passport.session({}) 

一切顺利,直到redis会话过期(我有这个设置了两个小时在我的configuration)。 会话过期后,我得到禁止的错误:

 Error: Forbidden at Object.exports.error (/code/node_modules/express/node_modules/connect/lib/utils.js:62:13) ... 

问题是,我不知道如何捕捉这个错误,并重置RedisSession(和CSRF令牌),结果,单页angular度前端看起来死了,它需要一个页面刷新抓住一个新的会话并重振东西。

其他人遇到这个问题? 提前致谢

你可以触摸会议,所以它不会过期…

 app.all('/*', function(req, res, next) { if ('HEAD' === req.method || 'OPTIONS' === req.method) return next(); req.session._garbage = new Date() req.session.touch() next(); }); 

所以,每当你的SPA POST或GET到任何'/ api / …'path,例如,你的会话过期可以推迟…

实际上,在我们最新的项目中,我们不再使用express.csrf()了,而是这样的一些forms:

 if('GET' isnt req.method) token = (req.body and req.body._csrf) or (req.query and req.query._csrf) or (req.headers["x-csrf-token"]) or (req.headers["x-xsrf-token"]) if token isnt req.session._csrfSecret return res.json 403, 'action forbidden: invalid application status, please refresh' else unless req.session._csrfSecret req.session._csrfSecret = cryptos.long_token() req.session.touch()