drf 认证失败统一响应码

现象

image

# 兜底认证,直接失败
class NoAuthentication(BaseAuthentication):
    def authenticate(self, request):
        raise AuthenticationFailed('认证失败')


class AuthenticationFailed(APIException):
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = _('Incorrect authentication credentials.')
    default_code = 'authentication_failed'

当认证失败应该显示401,不是403

解决方案(每个认证类加入def authenticate_header)

# 参数取值认证
class ParamsAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get('token')
        if not token:
            return
        return 'szw', token

    def authenticate_header(self, request):
        return 'API'


# header取值
class HeaderAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return
        return 'szw', token

    def authenticate_header(self, request):
        return 'API'


# 兜底认证,直接失败
class NoAuthentication(BaseAuthentication):
    def authenticate(self, request):
        raise AuthenticationFailed('认证失败')

    def authenticate_header(self, request):
        return 'API'

image

posted @ 2022-10-01 08:29  Sherwin_szw  阅读(47)  评论(0编辑  收藏  举报