天天看点

DRF中用户认证/权限认证 源代码分析

在讲解源码之前,先介绍一下 APIView和django中的View有什么不同

  • APIView是REST framework提供的所有视图的基类,继承自Django的View父类。

APIView与View的不同之处在于:

  • 传入到视图方法中的是REST framework的Request对象,而不是Django的HttpRequeset对象;REST framework 提供了Parser解析器,在接收到请求后会自动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进行parse解析,解析为类字典对象保存到Request对象中;
  • 视图方法可以返回REST framework的Response对象,视图会为响应数据设置(render)符合前端要求的格式;
  • 任何APIException异常都会被捕获到,并且处理成合适的响应信息;

    在进行dispatch()分发前,会对请求进行身份认证、权限检查、流量控制。

好的,关于用户认证的源代码分析,我们现在从`dispatch()`这个函数开始分析:

def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
--->  request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
 --->       self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
           

这个函数首先是给了我们一个注释:

.dispatch()`与Django的常规调度几乎相同,

但有额外的钩子,用于启动,结束和异常的处理

在dispatch类方法中,在request执行get\post\put\delete\等方法时候,会先对request请求进行用户验证,也就是如下2行代码:

1:request = self.initialize_request(request, *args, **kwargs)
2:self.initial(request, *args, **kwargs)
           

request = self.initialize_request(request, *args, **kwargs)

关于第一行代码

initialize_request

,从字面意思来看,就是对请求来的request,进行再次初始化封装,得到初始化后request,那就看看是如何进行初始化的:

def initialize_request(self, request, *args, **kwargs):
        """
        Returns the initial request object.
        """
        parser_context = self.get_parser_context(request)

        return Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )

           

嗯,这个函数里面的注释是验证了刚才的说法,这个是用来初始化请求对象的:

先分析这一段代码

parser_context = self.get_parser_context(request)

,我们可以通过这个函数的返回值看到,它是返回的一个字典类型的数据

def get_parser_context(self, http_request):
        """
        Returns a dict that is passed through to Parser.parse(),
        as the `parser_context` keyword argument.
        """
        # Note: Additionally `request` and `encoding` will also be added
        #       to the context by the Request object.
        return {
            'view': self,
            'args': getattr(self, 'args', ()),
            'kwargs': getattr(self, 'kwargs', {})
        }
           

在进行字典格式转换之后,

initialize_request

方法最终返回一个django自己封装的Request:

return Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )
           

来细看一下它这个Request在返回的时候,做了哪些事情:

1:

parsers=self.get_parsers()

是获取解析器(用来解析通过get_parser_context构造的字典数据的)

DRF中用户认证/权限认证 源代码分析
DRF中用户认证/权限认证 源代码分析

2:parser_context=parser_context是构造好的原生request封装的字典格式数据

3:

negotiator=self.get_content_negotiator()

一个内容协商类,它决定如何为响应选择一个呈现器,给定一个传入请求 ;

DRF中用户认证/权限认证 源代码分析
DRF中用户认证/权限认证 源代码分析

4:

authenticators=self.get_authenticators()

是获取

[auth() for auth in self.authentication_classes]

认证列表,里面是存放的一个个认证类对象;

get_authenticators方法如下,最后跟代码定位到如下键值对

DRF中用户认证/权限认证 源代码分析
DRF中用户认证/权限认证 源代码分析

我们可以先看一下父类

BaseAuthentication

的代码,如下,里面有2个方法,也就是进行认证,我们可以利用此来扩充校验认证规则

DRF中用户认证/权限认证 源代码分析

get_authenticators

方法就是去遍历继承类SessionAuthentication、BasicAuthentication的子类的列表,里面是一个一个子类对象,因为在列表推导是中

[auth() for auth in self.authentication_classes]

通过auth()获取类的实例对象;(其实这里面还有关于局部配置和全局配置,简单理解就是:单纯在某个类视图里面的配置,还是在settings.py中配置的,下一次会有进一步说明,get_authenticators会从自身找寻,查询不到,在去全局配置中查找)。

好的

request = self.initialize_request(request, *args, **kwargs)

在此告一段落,现在开始说

self.initial(request, *args, **kwargs)

self.initial(request, *args, **kwargs)

def initial(self, request, *args, **kwargs):
        """
        Runs anything that needs to occur prior to calling the method handler.
        """
        self.format_kwarg = self.get_format_suffix(**kwargs)

        # Perform content negotiation and store the accepted info on the request
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg

        # Determine the API version, if versioning is in use.
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        # Ensure that the incoming request is permitted
        self.perform_authentication(request)
        self.check_permissions(request)
        self.check_throttles(request)
           

这个注释挺好玩的:

在调用方法处理程序之前运行需要发生的任何事情。

我们来着重看一下我们需要了解的信息,也就是最后三段代码的用户认证、权限认证、访问频率控制(本篇不做说明):

1.self.perform_authentication(request)  用户认证
           
DRF中用户认证/权限认证 源代码分析

哈哈,真是惊讶,就一段代码

request.user

, 其实看到这里,我们应该知道,这个user肯定是被@property装饰过的,不然是不可能被直接调用而且不加任何括号;可以在DRF中找一下这个Request中带有@property的user:

DRF中用户认证/权限认证 源代码分析
@property
    def user(self):
        """
        Returns the user associated with the current request, as authenticated
        by the authentication classes provided to the request.
        """
        #判断当前类中是否有已经认证过的user
        if not hasattr(self, '_user'):
            #没有认证则去认证
            self._authenticate()
        #认证过了直接返回
        return self._user
           

没有认证的话,就需要调用Request类中的_authenticate()方法进行认证

def _authenticate(self):
        """
        Attempt to authenticate the request using each authentication instance
        in turn.
        """
        #遍历request对象中封装的Authentication对象
        for authenticator in self.authenticators:
            try:
                #调用Authentication对象中的authenticate方法,必须要有这个方法不然抛出异常
                #当然Authentication类一般有我们自己定义,实现这个方法就可以了
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple
                return

        self._not_authenticated()
           
2.  self.check_permissions(request)  权限认证
           
DRF中用户认证/权限认证 源代码分析
#检查权限
    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        #self.get_permissions()得到的是一个权限对象列表
        for permission in self.get_permissions():
            #在自定义的Permission中has_permission方法是必须要有的
            #判断当前has_permission返回的是True,False,还是抛出异常
            #如果是True则表示权限通过,False执行下面代码
            if not permission.has_permission(request, self):
                #为False的话则抛出异常,当然这个异常返回的提示信息是英文的,如果我们想让他显示我们自定义的提示信息
                #我们重写permission_denied方法即可
                self.permission_denied(
                    #从自定义的Permission类中获取message(权限错误提示信息),一般自定义的话都建议写上,如果没有则为默认的(英文提示)
                    request, message=getattr(permission, 'message', None)
                )
           

#self.get_permissions()得到的是一个权限对象列表,如下图

DRF中用户认证/权限认证 源代码分析
DRF中用户认证/权限认证 源代码分析

如果has_permission位False执行下面的代码

def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            #没有登录提示的错误信息
            raise exceptions.NotAuthenticated()
        #一般是登陆了但是没有权限提示
        raise exceptions.PermissionDenied(detail=message)
           

继续阅读