郭卫东 发表于 2022-10-25 20:21:55

rest_framework认证源码分析

认证源码分析

位置 :

APIVIew----》dispatch方法---》self.initial(request, *args, **kwargs)---->有认证,权限,频率三个版块
分析:

只读认证源码: self.perform_authentication(request)---》
self.perform_authentication(request)就一句话:request.user,需要去drf的Request对象中找user属性(方法)---》
Request类中的user方法,刚开始来,没有_user,走 self._authenticate()
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025180723586-129890889.png
核心:Request类的 _authenticate(self):
1.在需要进行认证的视图类中添加(认证类是自己写的类,该类继承了BaseAuthentication):
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025192446403-1511273466.png
2.此时apiview里的 authentication_classes就变成了自己第一步在视图函数类里定义的了,而不会去自己的配置文件里找
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025190946011-1407247310.png
3.然后正常执行到apiview里的dispatch方法:
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025190203621-1299672119.png
4.dispatch方法内部又调用了initialize_request方法,返回了一个新的request对象
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025190329028-1669387254.png
5.authenticators这个的值是get_authenticators()方法的返回值:返回值是一个个自己定义的继承了BaseAuthentication类的认证类对象
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025193551945-1014133168.png
6.Request类中的authenticators变成了自定义类的对象
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025194308816-589688156.png
7.在继续走apiview里的dispatch方法里的initial方法
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025194459347-347602398.png
8.进入认证模块的方法
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025194553561-302514578.png
9.进入新封装request对象里
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025194706501-1805263120.png
https://img2022.cnblogs.com/blog/2947776/202210/2947776-20221025194801207-2029051508.png
10.核心_authenticate方法
def _authenticate(self):
    # self是Request对象,所以去Request对象里找authenticators,
    # 最后self.authenticators的结果就是一个列表,列表里面是一个个自定义认证类的对象
    for authenticator in self.authenticators:
      try:
            # 此时authenticator就是认证类的对象,对象调用了authenticate方法,这个方法是需要我们在认证类里重新写的
            # 这个方法有两个返回值
            user_auth_tuple = authenticator.authenticate(self)
      except exceptions.APIException:
            self._not_authenticated()
            raise

      if user_auth_tuple is not None:
            self._authenticator = authenticator
            # 这两个返回值给了Request对象,就是request.user和request.auth(这就是为什么要求自己重新写的authenticate方法要有两个返回值了)
            self.user, self.auth = user_auth_tuple
            return

    self._not_authenticated()
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: rest_framework认证源码分析