【发布时间】:2014-08-26 01:52:36
【问题描述】:
我正在使用带有 express 的 nom 的 csurf 模块。自过去 3 天以来,一切都运行良好。现在每次我发布表单时都会收到无效的 csrf 令牌错误。我正在使用最新版本的 csurf 和 express。
我的 app.js 设置:
var csrf = require('csurf');
...
app.use(csrf());
...
app.use(function (req, res, next) {
res.locals = {
csrf: req.csrfToken(),...
我的玉模板:
form(role='form', method='post', action='/auth')
input(type='hidden', name='_csrf', value='#{csrf}')
...
input.btn.btn-success.btn-block(type='submit')
这是我经常遇到的错误:
Error: invalid csrf token
at createToken (/Users/.../.../.../.../node_modules/csurf/index.js:107:19)
at /Users/.../.../.../.../node_modules/csurf/index.js:91:7
at Object.<anonymous> (/Users/.../.../.../.../node_modules/csurf/node_modules/csrf-tokens/node_modules/uid-safe/index.js:13:7)
at Object.ondone (/Users/.../.../.../.../node_modules/newrelic/node_modules/continuation-local-storage/node_modules/async-listener/glue.js:177:31)
据我了解,此错误在我启动服务器并出现“没有打开的连接”错误后出现。
【问题讨论】:
-
检查您调用中间件的顺序。您可能以错误的顺序调用中间件。确保您的
csrf中间件和您对res.locals的分配发生在use(app.router)之前。 -
@adamK,我已经检查过了。一切都按需要的顺序排列。
-
你解决了这个问题了吗?我的 csrf 也不知为何突然停止工作。
-
@Charminbear,是的,我解决了这个问题。您可能使用安全 cookie。在你的 app.js 文件中检查这个。在我的浏览器中检查 cookie 后,我找到了解决方案(它们不是为这个网站设置的)。
标签: javascript node.js security