在单个页面上为多种表单生成CSRF令牌 [英] Generating CSRF tokens for multiple forms on a single page

查看:157
本文介绍了在单个页面上为多种表单生成CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在表单中生成一个 CSRF 令牌,以防止跨站点请求伪造。看起来像这样:

I am currently generating a CSRF token in my forms to prevent cross-site request forgery. It looks like:

<form method="post" action="action.php">
   <input type="hidden" id="security_token" name="security_token" value="gTt96phAcretR99rafEjepHebrEZadEdezadagaZ3gAS5es33WReJeZaMADU2AWr" />
   ...
</form>

问题是我在一个页面上有多个表单。我必须为每个表单创建一个安全令牌,以便 security_token_1 security_token_2 ,还是可以简单地代替生成安全令牌在表单内部,将其附加到整个 body 标记的属性中,例如:

The problem is that I have multiple forms on a single page. Must I create a security token for each form so security_token_1, security_token_2, or can I simply instead of generating the security token inside of forms, append it to a property to the entire body tag like:

<body data-csrf-token="gTt96phAcretR99rafEjepHebrEZadEdezadagaZ3gAS5es33WReJeZaMADU2AWr">
...
</body>

这是不安全的吗?因为我可以将安全令牌简单地附加到body元素上,而不用处理多个安全令牌,所以它大大简化了事情。

Is this insecure in any way? It simplifies things quite a bit, since I can simply append the security token to the body element instead of dealing with multiple security tokens.

感谢您的见解和评论。 / p>

Thanks for the insight and comments.

推荐答案

对于这两种形式,您都没有真正的理由,因为每种形式都有一个隐藏字段拥有相同 name 属性的表单。

There really isn't any reason you can't have the same generated token for both forms, with each hidden field in each form having the same name attribute.

毕竟,您真正要验证的是表单请求是来自具有有效会话的用户的入站邮件,并且一次只能主动发布一种表单。因此,您正在将发布的令牌与用户会话中存储的令牌进行比较。这样做的令牌值不必超过一个。

After all, what you are really trying to validate is that a form request is inbound from a user with a valid session, and only one form is going to be actively posted at a time. Thus you are comparing the token posted against a token stored in session for the user. There need not be more than one token value in order to do this.

对于需要基于AJAX帖子更新令牌的情况,您需要执行的操作如您所说,是将新创建的令牌传递回AJAX响应中,然后将隐藏字段值更新为新的令牌值。

For your case of needing to update the tokens based on AJAX posts, what you would need to do is, as you say, pass the newly created token back in the AJAX response, then update the hidden field values to the new token value.

这篇关于在单个页面上为多种表单生成CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆