关于jwt认证返回数据格式处理
代码如下,自定义认证类:
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from utils import constant
class JWTAuthentication(JSONWebTokenAuthentication):
def get_jwt_value(self, request):
try:
value=super().get_jwt_value(request) #jwt默认认证类,如果不传入AUTHORIZATION请求头,不会抛出异常直接返回none
if value is None: # 只要认证不通过全部抛出异常
raise AuthenticationFailed('无效的JWT token')
except AuthenticationFailed as e:
# 统一处理认证失败异常返回,格式统一,方便前端处理异常信息
raise AuthenticationFailed(detail={
'status_code': constant.AUTH_FAIL,
'message': '用户未登录或登录信息失效,请重新登录',
'data': ""
})
浙公网安备 33010602011771号