DRF组件--认证

DRF---认证功能

自己定义一个认证类,其中类中必定要有authenticate方法

class MyAuthentication():
    def authenticate(self,request):
        token = request._request.GET.get('token')
        token_obj = model_UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise AuthenticationFailed('用户认证失败')
        return (token_obj.user,token_obj)       #返回的元组的第一个值,可在request.user里面调用,第二个在request.auth调用
    def authenticate_header(self,val):
        pass

然后再视图函数中,配置authentication_classes的列表,列表中就是各个认证类的类名

class Dog(APIView):
    authentication_classes = [MyAuthentication,]        #用户认证

如果想要全局使用认证,则直接在settings里面配置

REST_FRAMEWORK = {
    #全局使用的认证类
    'DEFAULT_AUTHENTICATION_CLASSES':['app01.utils.authentication.MyAuthentication',],
    'UNAUTHENTICATED_USER':None,        #匿名用户的request.user的值
    'UNAUTHENTICATED_TOKEN':None        #匿名用户的request.auth的值
}

匿名用户就是所有的认证类都没有通过的用户,叫做匿名用户。

 

 

注意事项

如果一个类根据请求方式不通,进行不同的认证方式,
比如post想进行a认证,get想进行b认证,或者c不进行认证,可以在视图函数CBV里,重写get_authenticators方法
class User(APIView):
    def get_authenticators(self):
        # 重写认证类
        if self.request.method == 'POST':   # post请求不需要认证
            return None
        return [checkAuthentication(),]     #其他的视图还需要继续认证,返回一个类的对象

 

posted @ 2022-11-27 23:40  powfu  阅读(38)  评论(0)    收藏  举报