You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:51:08