You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Django项目重置密码时出现CSRF cookie未设置403错误求助

Django + Vue 跨域重置密码请求CSRF 403错误排查与解决

问题背景

Vue前端部署在127.0.0.1:8080,Django后端运行在127.0.0.1:8000,已按文档配置CORS和CSRF参数,但发送重置密码POST请求时,仍返回Forbidden (CSRF cookie not set.):的403错误。


排查与解决方案

1. 确保CSRF Cookie已被正确写入

Django的CSRF Token需要先通过GET请求触发后端设置Cookie,前端才能读取到对应值。

  • 前端在发送POST请求前,先发起一次GET请求到重置密码接口:
    axios.get("/api/v1/reset_password/")
      .then(() => {
        // 再执行POST请求
        const csrftoken = this.getCookie('csrftoken');
        axios.defaults.headers.common['X-CSRFToken'] = csrftoken;
        axios.post("/api/v1/reset_password/", formData, {withCredentials: true})
        // ...后续逻辑
      })
    
  • 或单独新增获取CSRF Token的接口:
    # email_app/views.py
    from django.middleware.csrf import get_token
    from rest_framework.decorators import api_view
    from rest_framework.response import Response
    
    @api_view(['GET'])
    def get_csrf_token(request):
        return Response({'csrfToken': get_token(request)})
    
    对应路由配置:
    # email_app/urls.py
    path('get_csrf/', views.get_csrf_token),
    
    前端先请求该接口获取Token,再设置到请求头。

2. 修复Cookie跨域配置

跨域场景下,必须调整Cookie的SameSite属性,在settings.py中修改:

SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

注意:本地HTTP环境下,Chrome等浏览器会拒绝SameSite=None的Cookie,需在浏览器chrome://flags/中开启Insecure origins treated as secure,并添加http://127.0.0.1:8080。

3. 修正前端Axios配置

跨域携带Cookie必须开启withCredentials:

// 全局配置
axios.defaults.withCredentials = true;

// 或单独请求配置
axios.post("/api/v1/reset_password/", formData, {
    withCredentials: true
})

同时修复getCookie方法中的HTML转义字符:

getCookie(name) {
   var cookieValue = null;
   if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
         var cookie = jQuery.trim(cookies[i]);
         if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
         }
      }
   }
   return cookieValue;
}

4. 优化视图异常处理

当前视图中User.objects.get(email=email)会抛出User.DoesNotExist异常,需捕获避免服务崩溃:

# email_app/views.py
try:
    user = User.objects.get(email=email)
except User.DoesNotExist:
    return Response({"error": "该邮箱未注册"}, status=status.HTTP_404_NOT_FOUND)

内容的提问来源于stack exchange,提问作者Kenshima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:15:04