2017-03-09 84 views
0

當我添加對CSRF令牌的支持以保持提交的安全性時,我遇到了與我的多部分表單有關的問題。我在我的app.js文件中將CSRF代全球設置爲我的req對象,並且除了multipart以外沒有任何其他類型的Web表單存在問題。我已經閱讀了這個與multer有關的常見問題,並且涉及將CSRF與multer設置一起放置,或者將其作爲查詢提交。由於安全原因,我寧願不使用附加查詢的方法,而寧願查看如何修復我的設置以像我的其他表單一樣運行。CSRF和Multer - 無效的CSRF令牌錯誤

錯誤消息:

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> 

回答

0

喜:)這是一個有點晚了,但(首先我很可能不是一個很好的講英語的人,所以如果你看到任何語法或speling錯誤使用

{try(){understand()}catch(e){/*do nothing :)*/}} 

方法:))

我上個月有你的問題,它是如此糟糕,我無法找到一個很好的答案

但在這裏,你:)))(老實說,我不太會在閱讀其他代碼,所以閱讀我的答案,並找出如何編輯你的代碼)

老實說,如果你想使用通常的發佈表單方法沒有好的答案(有一種方法,建議你先得到和保存文件,然後檢查它的csrf,我真的不喜歡太多),但如果你願意做一點硬前端JavaScript,那麼你是在你的美好的一天:

整個想法是設置一個標題爲您的表單,然後將其發送(全部採用AJAXJQuery的):

這裏是你怎麼是個小小的例子應該這樣做:

$.ajax({ 
    cache: false, 
    type: 'POST', 
    url: 'the URL you want to post to', 
    contentType: "what ever you want", 
    headers: {"X-CSRF-TOKEN": csrfToken}, 
    data: your data, 
    success: function (res) { 
     some code after you get a response from server 
     console.log(res) 
    } 
})