且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSRF令牌-如何正确实施?

更新时间:2023-01-26 10:14:05

您可以执行任何一项操作。这取决于您想要的安全级别。

You can do either. It depends on the level of security you want.

OWASP企业安全API(ESAPI)使用每个用户会话单个令牌方法。假设您没有XSS漏洞并且会话超时时间很短,那么这可能是一种非常有效的方法。如果您允许会话保持几天或几周的生命,那么这不是一个好方法。

The OWASP Enterprise Security API (ESAPI) uses the single token per user session method. That is probably a pretty effective method assuming you have no XSS holes and you have reasonably short session timeouts. If you allow sessions to stay alive for days or weeks, then this is not a good approach.

我个人并不认为很难为每个表单的每个实例使用不同的令牌。我将具有键值对的结构存储在用户的会话中。每个项目的键是表单的ID,值是包含令牌和该令牌的到期日期的另一个结构。通常,我只允许令牌生存10-20分钟,然后令牌过期。对于更长的表格,我可能会给它一个较长的到期时间。

Personally, I do not find it difficult to use a different token for each instance of each form. I store a structure in the user's session with key-value pairs. The key for each item is the ID of the form, the value is another structure that contain the token and an expiry date for that token. Typically I will only allow a token to live for 10-20 minutes, then it expires. For longer forms I may give it a long expiry time.

如果您希望能够在同一会话中的多个浏览器选项卡中支持相同的表单,那么我的方法将变得有些棘手,但仍然可以轻松实现唯一的表单ID。

If you want to be able to support the same form in multiple browser tabs in the same session, then my method becomes a little trickery but could still be easily done by having unique form IDs.