且构网

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

单页应用程序和 CSRF 令牌

更新时间:2023-02-15 07:40:44

客户端 (SPA)

您只需每个会话一次获取 CSRF 令牌.您可以在浏览器中保留它并在每个(非 GET)请求中发送它.

Client side (SPA)

You only need to grab the CSRF token once per session. You can hold onto it in the browser and send it on every (non-GET) request.

Rails 似乎会在每个请求上生成一个新的 CSRF 令牌,但它会接受来自该会话的任何生成的令牌.实际上,它只是对每个请求使用一次性填充来屏蔽单个令牌,以防止 SSL BREACH 攻击.更多详情请访问 https://***.com/a/49783739/2016618.您无需跟踪/存储这些令牌.

Rails will appear to generate a new CSRF token on every request, but it will accept any generated token from that session. In reality, it is just masking a single token using a one-time pad per request, in order to protect against SSL BREACH attack. More details at https://***.com/a/49783739/2016618. You don't need to track/store these tokens.

我强烈建议使用 Rails 的 protect_from_forgery 指令,而不是自己在标头中编码 CSRF 令牌.它将为每个请求生成不同的掩码令牌.

I strongly suggest using Rails's protect_from_forgery directive rather than encoding the CSRF token in a header yourself. It will generate a different masked token per request.

你当然可以不用那么多代码自己重现这个,但我不明白你为什么需要这样做.

You can certainly reproduce this yourself with not that much code, but I don't see why you'd need to.

是的!如果您使用 cookie 进行身份验证,则需要 CSRF 保护.这是因为 cookie 随每个请求一起发送,因此恶意网站可以向您的站点发送 POST 请求并代表登录用户执行请求.CSRF 令牌阻止了这种情况,因为恶意站点不会知道 CSRF 令牌.

Yes! If you are authenticating with a cookie, you need CSRF protection. This is because cookies are sent with every request, so a malicious website could send a POST request to your site and perform requests on behalf of a logged in user. The CSRF token prevents this, because the malicious site won't know the CSRF token.