Django无法从cookie中获取csrf_token

Django无法从cookie中获取csrf_token

Django 无法从 cookie 中获取 csrf_token

Django 默认在后端加载了 CSRF 验证中间件,会对非 get 类型请求进行 CSRF 验证,也就是校验请求头或者请求体中是否存在正确的 csrf token,若不存在或者 csrf token 错误,会拒绝请求。

今天在通过 axios 发送 post 请求过程中遇到了一个很令人窒息的问题,在 JS 中无法获取到 cookie 中的 csrf_token。查阅了一些资料,发现出现该问题的原因是 Django 默认会对 CSRF_COOKIE_USED 参数进行检查,若没有设置,中间件会直接返回响应体。总共有三种解决办法,如下所示:

  1. 手动调用 get_token(request)rotate_token(request) 方法:

    from django.middleware.csrf import get_token, rotate_token
    
    def test_view(request):
        get_token(request) # 两者选一
        # rotate_token(request) # 此方法会设置新的 csrf_token
        return render(request, "test.html")
    
  2. 在 HTML 模板中添加 {% csrf_token %}(最终采用了该方法):

    <!DOCTYPE html>
    <html lang="zh-cmn-Hans">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    
    {% csrf_token %}
    
    </body>
    </html>
    
  3. 在需要设置 cookie 的视图上添加装饰器 ensure_csrf_cookie()

    from django.views.decorators.csrf import ensure_csrf_cookie
    
    @ensure_csrf_cookie
    def test_view(request):
        return render(request, "test.html")
    

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://cangmang.xyz/articles/1680589024734