Authcookie未从浏览器发送到Django Backend

问题描述 投票:0回答:1

simplejwt

(均为
dj-rest-auth
提供)进行身份验证。当我使用API客户端(Bruno)提出API请求时,传递了包含JWT代币的auth cookie,并且服务器响应。但是,我在浏览器中无法实现同样的事情。
收到了身份验证cookie,但未通过随后的请求传递:

_auth and _refresh cookies received on login api call 小型前端JS:no cookies are sent with with (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中设置了CORS,Allow-Credentials等:

# dj-rest-auth settings --------------------------------- # src: https://medium.com/@michal.drozdze/django-rest-apis-with-jwt-authentication-using-dj-rest-auth-781a536dfb49 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 --------------------------------- # src: https://pypi.org/project/django-cors-headers/ CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = ( *default_headers, ) CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = 'None'
小型可复制示例:

安装django
tollow flow

本教程建立

dj-rest-auth
  • 创建用户
  • 在您的前端附带附件(例如,html中的脚本标签)
        
  • 我的主要问题是,登录端派发送的cookie并未保存在我的浏览器中。我应该先检查一下,以使这个问题更清楚。为了解决这个问题,我不得不修改我在前端提出的请求,以便也有
  • /api/login
  • 。这是因为默认情况下,在处理交叉原子API调用时,未保存收到的cookie。参见this
  • 答案 我固定的简单前端脚本看起来像这样:
credentials: 'include'
django django-rest-framework django-allauth django-rest-framework-simplejwt
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.