rest_framework认证源码分析

打印 上一主题 下一主题

主题 567|帖子 567|积分 1701

认证源码分析

位置 :

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()

核心:Request类的 _authenticate(self):
1.在需要进行认证的视图类中添加(认证类是自己写的类,该类继承了BaseAuthentication):

2.此时apiview里的 authentication_classes就变成了自己第一步在视图函数类里定义的了,而不会去自己的配置文件里找

3.然后正常执行到apiview里的dispatch方法:

4.dispatch方法内部又调用了initialize_request方法,返回了一个新的request对象

5.authenticators这个的值是get_authenticators()方法的返回值:返回值是一个个自己定义的继承了BaseAuthentication类的认证类对象

6.Request类中的authenticators变成了自定义类的对象

7.在继续走apiview里的dispatch方法里的initial方法

8.进入认证模块的方法

9.进入新封装request对象里


10.核心_authenticate方法
  1. def _authenticate(self):
  2.     # self是Request对象,所以去Request对象里找authenticators,
  3.     # 最后self.authenticators的结果就是一个列表,列表里面是一个个自定义认证类的对象
  4.     for authenticator in self.authenticators:
  5.         try:
  6.             # 此时authenticator就是认证类的对象,对象调用了authenticate方法,这个方法是需要我们在认证类里重新写的
  7.             # 这个方法有两个返回值
  8.             user_auth_tuple = authenticator.authenticate(self)
  9.         except exceptions.APIException:
  10.             self._not_authenticated()
  11.             raise
  12.         if user_auth_tuple is not None:
  13.             self._authenticator = authenticator
  14.             # 这两个返回值给了Request对象,就是request.user和request.auth(这就是为什么要求自己重新写的authenticate方法要有两个返回值了)
  15.             self.user, self.auth = user_auth_tuple
  16.             return
  17.     self._not_authenticated()
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

郭卫东

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表