simplejwt
(均为
dj-rest-auth
提供)进行身份验证。当我使用API客户端(Bruno)提出API请求时,传递了包含JWT代币的auth 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 :(")
}
})();
# 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'
小型可复制示例:
安装djangotollow flow
dj-rest-auth
/api/login
credentials: 'include'