django - 打开新的浏览器选项卡会使 Django 的 CSRF token 失效,从而阻止表单提交

标签 django csrf django-1.10

在第二个浏览器选项卡中打开 Django 1.10 应用程序会刷新 CSRF token 。这会破坏第一个选项卡中的所有表单 - 即,无法再提交之前打开的表单,因为旧的 CSRF token 现在无效。

如何避免这种行为?

分步示例:

  1. 用户正在选项卡 A 中查看表单。
  2. 用户在选项卡 B 中打开应用程序。
  3. 用户返回选项卡 A 并尝试提交表单。
  4. 错误:禁止 (403)。 CSRF验证失败。请求已中止。

一些细节:

我真的很想允许在应用程序中进行多选项卡浏览。

Django 1.10 release notes记录对 CSRF 机制的更改:

To protect against BREACH attacks, the CSRF protection mechanism now changes the form token value on every request (while keeping an invariant secret which can be used to validate the different tokens).

Django 的 1.9 CSRF documentation对可用性问题有很好的描述。此段落已在 1.10 CSRF documentation 中删除,但它似乎描述了我遇到的确切问题:

Why not use a new token for each request?

Generating a new token for each request is problematic from a UI perspective because it invalidates all previous forms. Most users would be very unhappy to find that opening a new tab on your site has invalidated the form they had just spent time filling out in another tab or that a form they accessed via the back button could not be filled out.

最佳答案

如果您在 View 中使用 @csrf_protect 装饰器,请尝试使用 @csrf_exempt 装饰器。

views.py之前:

    from django.views.decorators.csrf import csrf_protect

    @csrf_protect
    def view(request):
         # Render Something

views.py之后:

    from django.views.decorators.csrf import csrf_exempt

    @csrf_exempt
    def view(request):
         # Render Something

抱歉回复晚了。 我希望迟到总比不到好。

关于django - 打开新的浏览器选项卡会使 Django 的 CSRF token 失效,从而阻止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43296162/

相关文章:

python - django链表对象过滤器

java - 如何在 Liferay 中启用 CSRF 保护

asp.net - 反CSRF cookie?

python - 禁止 Django 自引用外键指向自身对象

python-2.7 - Django : Can't access model attributes

Django:覆盖表单中的 clean() 方法 - 关于引发错误的问题

django - 如何更改第三方 Django 应用程序的字段或模型属性?

python/django 正则表达式和包含 '#' 符号的 unicode 字符串

django - CSRF django nginx 与来自 cloudflare 的 ssl

python - 如何在 Django 表单中添加 GenericRelation 字段