如何在Django中自定义JWTAuthentication的Token无效JSON响应
修改JWTAuthentication默认错误响应方案
1. 自定义JWT认证类
继承JWTAuthentication并重写authenticate方法,捕获JWT相关认证异常后返回自定义格式的响应:
# account应用/views.py from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework_simplejwt.exceptions import InvalidToken, AuthenticationFailed from rest_framework.response import Response from rest_framework import status class CustomJWTAuthentication(JWTAuthentication): def authenticate(self, request): try: # 执行原有认证逻辑 return super().authenticate(request) except (InvalidToken, AuthenticationFailed) as e: # 返回自定义错误响应 return Response( { "message": str(e), "status": status.HTTP_401_UNAUTHORIZED }, status=status.HTTP_401_UNAUTHORIZED )
2. 更新全局认证配置
在settings.py中替换默认的JWT认证类为自定义类:
# settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'account.views.CustomJWTAuthentication', # 替换为自定义类的完整路径 ) }
3. 验证效果
当Token无效、过期或不符合要求时,接口将返回你期望的响应格式:
{ "message": "Given token not valid for any token type", "status": 401 }
内容的提问来源于stack exchange,提问作者Yash Marmat
相关产品推荐
相关产品推荐

