DRF之认证

发布时间 2023-04-18 17:08:10作者: 阿勒泰的鱼

1. 基于DRF自己写认证类

1.1基于DRF的 BaseAuthentication

使用的基类:from rest_framework.authentication import BaseAuthentication

from rest_framework.exceptions import APIException
from rest_framework.exceptions import AuthenticationFailed
class App01Auth(BaseAuthentication):
    def authenticate(self, request):
        # 如果认证通过返回两个值
        # 没通过抛异常
        token=request.GET.get('token')
        if token:
            user_token=UserToken.objects.filter(token=token).first()
            # 认证通过
            if user_token:
                return user_token.user,token
                #  这样吧user对象存到了request.user里。token存到了request.auth里。可以全局使用
            else:
                raise AuthenticationFailed('认证失败')
        else:
            raise APIException('没有token')

1.2  配置 分为全局配置和局部配置

   全局使用 ,局部使用

    局部使用
class BookModelViewSet(ModelViewSet):
authentication_classes = [App01Auth]
全局使用
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES': [
'app01.auth_1.App01Auth'
]}
但是这样就登录不了了。
在登录那里写一个空的列表 authentication_classes = []
这就行了。