django-rest-framework认证源码解读和自定义一个认证类

流程图:

1.  调用rest-framework中的dispatch方法

2. 调用 initialize_request方法,对原生request对象进行封装

3. 调用 get_authenticators 获取认证类对象列表

4. 封装request对象时,就会把原生request对象和获取到的认证类对象列表赋给request._request和request.authenticators

5. 至此,新request对象封装完成,认证校验入口

6. 调用perform_authentication方法进行认证的校验

7. 认证校验里会调用新request对象的user方法

8. user方法里会调用_authenticate方法

9. _authenticate方法里会遍历新request对象的authenticators属性,也就是认证类的实例对象列表,然后调用认证类实例的authenticate方法

10. 下面我们自已定义一个认证类

from rest_framework.views import APIView
from rest_framework import exceptions

class MyAuthentication(object):
    def authenticate(self, request):
        token = request._request.GET.get("token")
        # 获取用户名和密码,去数据库校验
        if not token:
            # 认证失败,抛出异常
            raise exceptions.AuthenticationFailed("用户未认证")
        # 认证成功,此处要求是返回一个元组,(用户名, token)
        return ("mayanan", token)

    def authenticate_header(self, request):
        pass


class DogAPIView(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        # 此处的打印的就是认证类中的authenticate方法返回的元组的两个值
        print(request.user, request.auth)
        return HttpResponse("获取Dog订单")

    def post(self, request):
        return HttpResponse("新增Dog订单")

    def put(self, request):
        return HttpResponse("修改Dog订单")

    def delete(self, request):
        return HttpResponse("删除Dog订单")

猜你喜欢

转载自blog.csdn.net/weixin_42289273/article/details/115308013