Django应用JWT及Refresh Token存入Cookie后,前端为何无法完成认证?
问题分析与解决方案
你的核心问题是:rest_framework_simplejwt默认的JWTAuthentication只会从请求头的Authorization字段(Bearer Token格式)读取令牌,不会自动读取Cookie里的jwt_token,所以即使浏览器Cookie里有令牌,后端认证流程也拿不到,导致request.user始终是匿名用户,返回未认证错误。
下面是具体解决步骤:
1. 自定义JWT认证类,从Cookie读取令牌
在你的Django应用下创建authentication.py文件,写入以下代码:
from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework import exceptions class CookieJWTAuthentication(JWTAuthentication): def authenticate(self, request): # 从Cookie中获取access token token = request.COOKIES.get('jwt_token') if not token: return None try: # 验证令牌 validated_token = self.get_validated_token(token) user = self.get_user(validated_token) return (user, validated_token) except exceptions.AuthenticationFailed: return None
2. 更新settings.py中的认证配置
把原来的rest_framework_simplejwt.authentication.JWTAuthentication替换成你自定义的认证类:
REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( # 替换为自定义的认证类,注意路径要对应你的应用名 'your_app_name.authentication.CookieJWTAuthentication', ) }
3. 优化登录接口的Cookie设置(可选但重要)
登录时设置Cookie时,建议加上安全相关的参数,尤其是跨域场景下:
response.set_cookie( 'jwt_token', str(refresh.access_token), httponly=True, # 防止XSS攻击,JS无法读取该Cookie secure=True, # 仅在HTTPS下传输,生产环境建议开启 samesite='None' if is_cross_domain else 'Lax', # 跨域时设为None,非跨域用Lax max_age=5*60, # 和ACCESS_TOKEN_LIFETIME保持一致 path='/' ) response.set_cookie( 'refresh_token', str(refresh), httponly=True, secure=True, samesite='None' if is_cross_domain else 'Lax', max_age=24*60*60, # 和REFRESH_TOKEN_LIFETIME保持一致 path='/' )
注:如果是跨域场景,需要确保前端域名在
CORS_ALLOWED_ORIGINS中,并且开启跨域凭证支持:CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "https://your-frontend-domain.com", ]
4. 验证接口
重启Django服务后,再用Axios发起请求,此时后端会从Cookie中读取jwt_token并完成认证,就能正常返回用户Profile数据了。
内容的提问来源于stack exchange,提问作者boyenec
相关产品推荐
相关产品推荐

