【发布时间】:2017-07-29 21:11:42
【问题描述】:
当我添加对 CSRF 令牌的支持以确保提交安全时,我的多部分表单遇到了问题。我已将 CSRF 生成全局设置为我的 app.js 文件中的 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>
【问题讨论】:
标签: node.js express csrf multer