DRF登录认证组件

DRF登录认证组件

1.写一个登录认证类(类名随意,类中的方法名固定)

from app01 import models
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication


class Auth(BaseAuthentication):

    def authenticate(self,request):
        token = request.query_params.get('token')
        res = models.Token.objects.filter(token=token).first()
        if res:
            #放回的res.user就是将user添加到request中user中,res会添加到request的auth中
            return res.user,res
        else:
            raise exceptions.APIException('您还没有登录!')

2.全局使用

​ 在setting中配置

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ['app01.AuthAPI.Auth']
}

​ 每次走视图行数之前都会先走认证类

3.局部禁用(在视图类中添加)

authentication_classes = [ ]

例如:

​ 这样Login视图类就不会使用Auth认证

class Login(APIView):
    authentication_classes = [ ]
    def post(self,request):
        user = models.User.objects.filter(name=request.data.get('name'),pwd=request.data.get('pwd')).first()
        if not user:
            return JsonResponse({'msg':'用户名或者密码错误!'})
        else:
            token = uuid.uuid4()
            models.Token.objects.update_or_create(user=user,defaults={'token':token})
            return JsonResponse({'msg':'登录成功!','token':token})

4.局部使用

​ 如果要实现局部使用就不能在setting中配置了,

​ 在要使用的视图类中添加如下字段

authentication_classes = [Auth, ]

​ 例如:

class Login(APIView):
    authentication_classes = [Auth, ]
    def post(self,request):
        user = models.User.objects.filter(name=request.data.get('name'),pwd=request.data.get('pwd')).first()
        if not user:
            return JsonResponse({'msg':'用户名或者密码错误!'})
        else:
            token = uuid.uuid4()
            models.Token.objects.update_or_create(user=user,defaults={'token':token})
            return JsonResponse({'msg':'登录成功!','token':token})
原文地址:https://www.cnblogs.com/jianhaozhou/p/10114842.html