在SPA中登录后,CSRF令牌不正确,但是在刷新页面后正确 [英] CSRF token is incorrect after login in SPA, but correct after page refresh

查看:118
本文介绍了在SPA中登录后,CSRF令牌不正确,但是在刷新页面后正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用后端的django-rest-framework做SPA并使用django-rest-auth进行用户身份验证。

We make react SPA with django-rest-framework on backend and use django-rest-auth for user authentication.

用户登录后,我们向他显示变更配置文件数据的表格。当用户提交此表单时,我们在登录响应中从cookie中获取csrf令牌,并将其放入请求X-CSRFToken标头中。服务器响应令牌丢失或不正确。

When user has logged in, we show him form for change profile data. When user submit this form, we take csrf token from cookie in login response, and put them in request X-CSRFToken header. Server responses that token is missing or incorrect.

如果用户刷新页面并重复相同的操作,则csrf令牌正确且配置文件数据已更新。

If user refreshed the page, and repeated the same actions, csrf token is correct and profile data is updated.

如何解决此问题以及发生的原因?

How to solve this problem and why it occurs?

推荐答案

似乎正在发生这种情况:

It looks like this is happening:


  • 登录成功

  • 已创建cookie +令牌由CSRF API发送并返回到端点

  • 就绪状态将执行一些在API响应后未执行的代码

  • 证书已验证并且cookie +令牌是在GET请求期间和/或就绪状态回调中在数据库/应用程序配置/服务器端缓存中设置的

  • The login is successful
  • The cookie+token is created by the CSRF API and returned to the endpoint
  • The ready state executes some code not executed after the API response
  • The certificate is validated and the cookie+token is set in the database/app config/server-side cache during a GET request and/or by the ready state callback

由于在刷新之前没有GET请求,因此直到那时cookie + token才被集中存储。添加一个请求以模仿GET期间发生的情况,然后将其存储在当前正在被后续请求访问的位置。

Since there is no GET request until the refresh, the cookie+token is not centrally stored until then. Add a request to mimic what happens during the GET, then store it where it is currently being accessed for subsequent requests.

参考

为什么要为每个表单请求刷新CSRF令牌? -信息安全堆栈交换

CSRF保护-Flask-WTF 0.14

CSRFGuard 3配置-OWASP

春季安全性:跨站点请求伪造(CSRF)

跨站点请求伪造保护| Django文档| Django

ASP.NET MVC和Web页中的XSRF / CSRF防护| Microsoft文档

跨站点请求伪造已死!

仍然认为您不需要HTTPS?

这篇关于在SPA中登录后,CSRF令牌不正确,但是在刷新页面后正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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