【问题标题】:How to add assign csrf token in the HTML submit form如何在 HTML 提交表单中添加分配 csrf 令牌
【发布时间】:2018-05-11 15:32:00
【问题描述】:

我的网站目前处于 csurf 保护之下。

我已经为我所有的 ajax 调用分配了如下的 csrf 令牌

"/data/someAPI?_csrf="+ $("#_csrf").val 它适用于我拥有的所有功能。

但是现在我在写一个文件上传功能,网上大部分教程都是用sumbit形式来做的。

所以我写了类似的东西

Node.js

app.post('/upload', function(req, res) {
  if (!req.files)
    return res.status(400).send('No files were uploaded.');

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

已解决

HTML

<html>
  <body>
    <form ref='uploadForm' 
      id='uploadForm' 
      action='http://localhost:8000/upload?_csrf=<your_csrf_token>"' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <input type='submit' value='Upload!' />
    </form>     
  </body>
</html>

我直接在表单操作中分配了令牌,它工作正常。

【问题讨论】:

  • 为什么不像你在ajax电话中那样做呢?即以action 的形式定义令牌。
  • @aquaman 你的意思是我应该 把这行放在表格里吗?
  • 我的意思是将您的表单修改为action="/upload?_csrf=&lt;your_csrf_token&gt;"。好吧,您可以尝试其他选项中的建议。
  • 谢谢我解决了!!! @aquaman
  • 小问题,你首先如何获得那个 CSRF 令牌?

标签: javascript jquery ajax csrf


【解决方案1】:

您可以为_csrt 令牌添加隐藏字段。这是示例代码

<html>
  <body>
    <form ref='uploadForm' 
      id='uploadForm' 
      action='http://localhost:8000/upload' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <input type="hidden" name="_csrf" value="<your_csrf_token>" />
        <input type='submit' value='Upload!' />
    </form>     
  </body>
</html>

【讨论】:

  • @BhavaniSolanki : 在实现 CSRF 解决方案隐藏字段比较服务器端后,问题是,当打开具有相同 URL 的新选项卡时,隐藏字段为空。服务器端条件是如果 CSRF 隐藏字段为空,则其攻击.这是预期的行为吗?
猜你喜欢
  • 2018-10-08
  • 2019-07-28
  • 2015-04-29
  • 1970-01-01
  • 2016-12-20
  • 2012-11-19
  • 2014-06-19
  • 2016-07-04
  • 2016-12-08
相关资源
最近更新 更多