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

浏览器JS请求无法将Auth Cookie发送至Django后端问题排查

Django JWT Cookie认证:浏览器JS请求无法携带Cookie问题

我基于Django搭建后端,用allauth和simplejwt(通过dj-rest-auth集成)实现认证机制。使用Bruno等API客户端发送请求时,包含JWT令牌的认证Cookie能正常传递,服务器响应正常;但在浏览器中通过JavaScript发送请求时,却无法实现相同效果。

问题现象

认证Cookie已成功被浏览器接收,但后续请求中并未携带:

  • 登录API调用收到_auth和_refresh Cookie:
    登录API调用收到_auth和_refresh Cookie
  • 用户信息请求未携带Cookie,导致认证失败:
    用户信息请求未携带Cookie,导致认证失败

前端极简JS代码

(async () => {
    console.log("logging in...")

    const loginResponse = await fetch('http://127.0.0.1:8000/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: 'test',
            password: 'securepassword123'
        })
    })
    const loginData = await loginResponse.json();
    // response contains `set-cookie` headers
    // vv prints JSON containing "access", "refresh", "username", etc.
    console.log(loginData)

    if (!loginResponse.ok) {
        console.log('login failed :(')
        return
    }

    console.log("getting user info...")

    const userResponse = await fetch('http://127.0.0.1:8000/api/user', {
        credentials: 'include'
    });
    const userData = await userResponse.json();
    // vv prints `{detail: 'Authentication credentials were not provided.'}`
    console.log(userData)
    if (!userResponse.ok) {
        console.log("user data fetch failed :(")
    }
})();

Django配置代码

# dj-rest-auth settings ---------------------------------
SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
    )
}

# djangorestframework-simplejwt
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(hours=1),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
}

# dj-rest-auth
REST_AUTH = {
    "USE_JWT": True,
    "JWT_AUTH_COOKIE": "_auth",  # Name of access token cookie
    "JWT_AUTH_REFRESH_COOKIE": "_refresh", # Name of refresh token cookie
    "JWT_AUTH_HTTPONLY": False,  # Makes sure refresh token is sent
}

# cors ---------------------------------
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_HEADERS = (
    *default_headers,
)
CORS_ALLOW_CREDENTIALS = True
SESSION_COOKIE_SAMESITE = 'None'

极简复现步骤

  • 安装Django
  • 按教程配置dj-rest-auth
  • 创建测试用户
  • 在前端HTML的<script>标签中运行上述JS脚本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:34:56