Django中Authorization: Bearer none触发token无效错误的解决方法
要保留JWT认证功能同时处理Authorization: Bearer none的请求,你可以通过自定义JWT认证类拦截这种特殊情况,具体步骤如下:
1. 编写自定义认证类
在你的Django应用下新建一个auth.py文件,继承JWTAuthentication并重写authenticate方法,识别并处理Bearer none的请求头:
from rest_framework_simplejwt.authentication import JWTAuthentication class CustomJWTAuthentication(JWTAuthentication): def authenticate(self, request): auth_header = request.META.get('HTTP_AUTHORIZATION') # 匹配Bearer none的情况,忽略认证,返回匿名用户 if auth_header and auth_header.strip().lower() == 'bearer none': return None # 其他正常令牌请求走原认证逻辑 return super().authenticate(request)
2. 替换默认认证类
修改settings.py中的REST_FRAMEWORK配置,将默认的JWT认证类替换为你自定义的:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ["your_app_name.auth.CustomJWTAuthentication"], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], "TEST_REQUEST_DEFAULT_FORMAT": "json", 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, }
注意把your_app_name替换成你实际的应用名称。
3. 验证效果
当前端发送Authorization: Bearer none请求时,后端会将request.user设为匿名用户,不会再返回token_not_valid的错误,同时正常保留已登录用户的认证识别能力——你的retrieve方法里的逻辑会正常执行,匿名用户不会触发InteractionUserProblem的创建逻辑,已登录用户则会正常记录浏览行为。
内容的提问来源于stack exchange,提问作者Daler Hojimatov
相关产品推荐
相关产品推荐

