CSRF令牌不工作在nodejs表达 [英] CSRF token not working in nodejs express
问题描述
我使用nodejs,express开发一个简单的web应用程序,当我切换到会话和csrf,我的PUT,DELETE和POST请求失败。
与错误:
I am developing a simple web app using nodejs, express and when i switched to session and csrf, my PUT, DELETE and POST Requests are failing. with error:
错误:Forbidden在Object.exports.error(appFolder / node_modules / express / node_modules / connect / utils.js:63:13)at createToken(appFolder / node_modules / express / node_modules / connect / lib / middleware / csrf.js:82:55)
我看了这行,发现它调用 checkToken
function
调用defaultValue,在请求中查找csrf令牌,如下所示:
I looked at this line, and found that it calls checkToken
function
which calls the defaultValue which finds the csrf token in the request like this:
function defaultValue(req) {
return (req.body && req.body._csrf)
|| (req.query && req.query._csrf)
|| (req.headers['x-csrf-token'])
|| (req.headers['x-xsrf-token']);
}
这是给null或未定义的值,我的checkToken失败。
This was giving null or undefined value, and my checkToken was failing.
我的PUT请求是由骨干生成的,我只是发送模型的数据。所以我开始发送回cookie中的令牌。
我在cookie中设置令牌,如:
My PUT requests are generated by backbone and i just send the model's data. so i started sending back the token in cookie. I set the token in cookie like:
app.use(express.cookieParser());
app.use(express.session({
secret: '6767678376-3hudh-2u78di90-kjdu39i-jfujd'
}));
app.use(function(req,res,next) {
console.log("Body " + JSON.stringify(req.headers));
return next();
});
app.use(express.csrf());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
console.log(req.body);
res.cookie('x-csrf-token', req.csrfToken());
console.log('CSRF : ' + req.csrfToken());
//res.session._csrf = req.csrfToken();
return next();
});
并将 defaultValue(req)
更改为
function defaultValue(req) {
var csrf_token = (req.body && req.body._csrf)
|| (req.query && req.query._csrf)
|| (req.headers['x-csrf-token'])
|| (req.headers['x-xsrf-token']);
if(csrf_token)
return csrf_token;
// find in cookie.
if(!req.headers['cookie'])
return undefined;
var csrfTokenInCookie = (req.headers['cookie'].split('x-csrf-token='));
if(csrfTokenInCookie && (csrfTokenInCookie.length == 2)) {
return csrfTokenInCookie[1];
}
var xsrfTokenInCookie = (req.headers['cookie'].split('x-xsrf-token='));
if(xsrfTokenInCookie && (xsrfTokenInCookie.length == 2)) {
return xsrfTokenInCookie[1];
}
}
$ b $ p现在defaultValue正确地给出csrftoken标记, checkToken
失败。
档案在这里: csrf.js
我做错了什么?
或者如何无法产生正确的令牌?
Or how can it not generate back the right-token ?
推荐答案
p>您的问题是与Express不发送CSRF令牌回到POST / PUT / DELETE请求的标头。
Your issue is with Express not sending the CSRF token back in a header for POST/PUT/DELETE requests. Express's CSRF middleware is doing the correct thing in rejecting these requests when the header is missing.
这里有关于在Backbone中添加您需要的标题的信息:如何在使用Backbone.js发布数据时防止CSRF?
Here's info on adding the header you need in Backbone: How to protect against CSRF when using Backbone.js to post data?
这篇关于CSRF令牌不工作在nodejs表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!