我在为我的多部分表单添加CSRF令牌以保持提交安全时遇到了问题。我已经在我的
app.js
文件中将CSRF生成设置为全局的req
对象,并且除了multipart之外,没有其他类型的Web表单问题。我已经阅读过这是multer的常见问题,与CSRF的放置方式有关,要么与multer设置一起使用,要么将其附加为提交查询。出于安全原因,我不想采用附加查询的方法,而希望看到如何修复我的设置,使其像我的其他表单一样运行。
错误信息:
ForbiddenError: invalid csrf token
at csrf (/Users/user/Desktop/Projects/node/test-app/node_modules/csurf/index.js:112:19)
app.js:
var csrf = require('csurf');
....
//Set CSRF for Form Tokens
app.use(csrf());
app.use(function(req, res, next){
res.locals._csrf = req.csrfToken();
next();
});
路由:
var upload = multer({
storage: multerS3({
s3: s3,
bucket: options.Bucket,
contentType: multerS3.AUTO_CONTENT_TYPE,
acl: options.ACL,
key: function(req, file, cb){
var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
cb(null, req.user.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
}
}),
fileFilter: function(req, file, cb){
if(!file.originalname.match(/\.(jpg|jpeg|png|gif|csv|xls|xlsb|xlsm|xlsx)$/)){
return cb('One of your selected files is not supported', false);
}
cb(null, true);
}
}).array('fileUpload', 5);
appRoutes.route('/blog/create')
.get(function(req, res){
res.render('pages/app/blog-create.hbs',{
errorMessage: req.flash('error'),
csrfToken: req.csrfToken()
});
})
.post(function(req, res){
upload(req, res, function(err){
if(err){
req.flash('error', err);
res.redirect(req.get('referer'));
return;
}
models.Blog.create({
date: req.body.date,
title: req.body.title,
content: req.body.content,
userId: req.user.userId
}).then(function(){
req.flash('info', 'Blog was successfully created.');
res.redirect('/app');
});
})
});
视图:
<form action="/app/blog/create" method="post" enctype="multipart/form-data" id="blogSubmission">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
....
</form>