加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Django rest_framework 认证源码流程

发布时间:2020-12-15 17:20:28 所属栏目:大数据 来源:网络整理
导读:div id="cnblogs_post_body" class="blogpost-body" h1 class="title"一、请求到来后,都要先执行dispatch方法 p class="title"dispatch根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 dispatch(self,request,

<div id="cnblogs_post_body" class="blogpost-body">
<h1 class="title">一、请求到来后,都要先执行dispatch方法
<p class="title">dispatch根据请求方式的不同触发get/post/put/delete等方法

注意,APIView中的dispatch方法有很多的功能

dispatch(self,request,*args,**== request = self.initialize_request(request,**== self.default_response_headers
    <span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt;:
        </span><span style="color: #008000;"&gt;#</span><span class="secondtitle"&gt;第二步:</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;处理版权信息</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;认证</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;权限</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;请求用户进行访问频率的限制</span>
        self.initial(request,**<span style="color: #000000;"&gt;kwargs)

        </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Get the appropriate handler method</span>
        <span style="color: #0000ff;"&gt;if</span> request.method.lower() <span style="color: #0000ff;"&gt;in</span><span style="color: #000000;"&gt; self.http_method_names:
            handler </span>=<span style="color: #000000;"&gt; getattr(self,request.method.lower(),self.http_method_not_allowed)
        </span><span style="color: #0000ff;"&gt;else</span><span style="color: #000000;"&gt;:
            handler </span>=<span style="color: #000000;"&gt; self.http_method_not_allowed

        </span><span style="color: #008000;"&gt;#</span><span class="secondtitle"&gt; 第三步、执行:get/post/put/delete函数</span>
        response = handler(request,**<span style="color: #000000;"&gt;kwargs)

    </span><span style="color: #0000ff;"&gt;except</span><span style="color: #000000;"&gt; Exception as exc:
        response </span>=<span style="color: #000000;"&gt; self.handle_exception(exc)

    </span><span class="secondtitle"&gt;#第四步、</span><span style="color: #008000;"&gt; 对返回结果再次进行加工</span>
    self.response = self.finalize_response(request,response,**<span style="color: #000000;"&gt;kwargs)
    </span><span style="color: #0000ff;"&gt;return</span> self.response</pre>

<h1 class="title">二、上面是大致步骤,下面我们来具体分析一下
<h2 class="secondtitle">1、对request进行加工(添加数据)

我们来看看request里面都添加了那些数据

a、首先request = self.initialize_request(request,**kwargs)点进去,会发现:在Request里面多加了四个,如下

initialize_request(self,** parser_context = </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; Request( request,parsers</span>=self.get_parsers(),<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;解析数据,默认的有三种方式,可点进去看</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;self.get_authenticator优先找自己的,没有就找父类的</span> authenticators=self.get_authenticators(),<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;获取认证相关的所有类并实例化,传入request对象供Request使用</span> negotiator=<span style="color: #000000;"&gt;self.get_content_negotiator(),parser_context</span>=<span style="color: #000000;"&gt;parser_context )</span></pre>

b、获取认证相关的类的具体 authenticators=self.get_authenticators(),

[auth() auth self.authentication_classes]

c、查看认证的类:self.authentication_classes

authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

d、接着走进api_settings

api_settings = APISettings(None,DEFAULTS,IMPORT_STRINGS) #点击继承的DEFAULTS类
DEFAULTS =

e、导入了类看看类里面具体干了什么

rest_framework.authentication rest_framework.authentication BaseAuthentication

f、看到里面有个authenticate方法和authenticate_header方法

<span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate(self,request):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Authenticate the request and return a two-tuple of (user,token).
    </span><span style="color: #800000;"&gt;"""</span>
    <span style="color: #0000ff;"&gt;raise</span> NotImplementedError(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;.authenticate() must be overridden.</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)

</span><span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate_header(self,request):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Return a string to be used as the value of the `WWW-Authenticate`
    header in a `401 Unauthenticated` response,or `None` if the
    authentication scheme should return `403 Permission Denied` responses.
    </span><span style="color: #800000;"&gt;"""</span>
    <span style="color: #0000ff;"&gt;pass</span></pre>

具体处理认证,从headers里面能获取用户名和密码

=
<span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate(self,request):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Returns a `User` if a correct username and password have been supplied
    using HTTP Basic authentication.  Otherwise returns `None`.
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #000000;"&gt;
    auth </span>=<span style="color: #000000;"&gt; get_authorization_header(request).split()

    </span><span style="color: #0000ff;"&gt;if</span> <span style="color: #0000ff;"&gt;not</span> auth <span style="color: #0000ff;"&gt;or</span> auth[0].lower() != b<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;basic</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;:
        </span><span style="color: #0000ff;"&gt;return</span> None   <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;返回none不处理。让下一个处理</span>

    <span style="color: #0000ff;"&gt;if</span> len(auth) == 1<span style="color: #000000;"&gt;:
        msg </span>= _(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid basic header. No credentials provided.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;raise</span><span style="color: #000000;"&gt; exceptions.AuthenticationFailed(msg)
    </span><span style="color: #0000ff;"&gt;elif</span> len(auth) > 2<span style="color: #000000;"&gt;:
        msg </span>= _(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid basic header. Credentials string should not contain spaces.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;raise</span><span style="color: #000000;"&gt; exceptions.AuthenticationFailed(msg)

    </span><span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt;:
        auth_parts </span>= base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;:</span><span style="color: #800000;"&gt;'</span>)   <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;用partition切割,保留了分割项冒号</span>
    <span style="color: #0000ff;"&gt;except</span><span style="color: #000000;"&gt; (TypeError,UnicodeDecodeError,binascii.Error):
        msg </span>= _(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid basic header. Credentials not correctly base64 encoded.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;raise</span><span style="color: #000000;"&gt; exceptions.AuthenticationFailed(msg)

    userid,password </span>= auth_parts[0],auth_parts[2]  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 返回用户和密码</span>
    <span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; self.authenticate_credentials(userid,password,request)

</span><span style="color: #0000ff;"&gt;def</span> authenticate_credentials(self,userid,request=<span style="color: #000000;"&gt;None):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Authenticate the userid and password against username and password
    with optional request for context.
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #000000;"&gt;
    credentials </span>=<span style="color: #000000;"&gt; {
        get_user_model().USERNAME_FIELD: userid,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;password</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;: password
    }
    user </span>= authenticate(request=request,**<span style="color: #000000;"&gt;credentials)

    </span><span style="color: #0000ff;"&gt;if</span> user <span style="color: #0000ff;"&gt;is</span><span style="color: #000000;"&gt; None:
        </span><span style="color: #0000ff;"&gt;raise</span> exceptions.AuthenticationFailed(_(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid username/password.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;))

    </span><span style="color: #0000ff;"&gt;if</span> <span style="color: #0000ff;"&gt;not</span><span style="color: #000000;"&gt; user.is_active:
        </span><span style="color: #0000ff;"&gt;raise</span> exceptions.AuthenticationFailed(_(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;User inactive or deleted.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;))

    </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; (user,None)

</span><span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate_header(self,request):
    </span><span style="color: #0000ff;"&gt;return</span> <span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Basic realm="%s"</span><span style="color: #800000;"&gt;'</span> % self.www_authenticate_realm</pre>

g、当然restfulframework默认定义了两个类。我们也可以自定制类,自己有就用自己的了,自己没有就去找父类的了,但是里面必须实现authenticate方法,不然会报错。

  • 处理版权信息
  • 认证
  • 权限
  • 请求用户进行访问频率的限制

我们主要来看一下认证流程

认证流程:

a、首先self.initial(request,**kwargs)可以看到做了以下操作

initial(self,**= self.get_format_suffix(** </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Perform content negotiation and store the accepted info on the request</span> neg =<span style="color: #000000;"&gt; self.perform_content_negotiation(request) request.accepted_renderer,request.accepted_media_type </span>=<span style="color: #000000;"&gt; neg </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Determine the API version,if versioning is in use.</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;2.1 处理版本信息</span> version,scheme = self.determine_version(request,**<span style="color: #000000;"&gt;kwargs) request.version,request.versioning_scheme </span>=<span style="color: #000000;"&gt; version,scheme </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Ensure that the incoming request is permitted</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;2.2 认证</span>

<span style="color: #000000;"> self.perform_authentication(request)
<span style="color: #008000;">#<span style="color: #008000;"> 2.3 权限
<span style="color: #000000;"> self.check_permissions(request)
<span style="color: #008000;">#<span style="color: #008000;"> 2.4 请求用户进行访问频率的限制
self.check_throttles(request)

b、我们先来看认证,self.perform_authentication(request) 具体干了什么,按住ctrl点击进去

Note that if you override this and simply 'pass',then authentication will instead be performed lazily,the first time either `request.user` or `request.auth` is accessed. </span><span style="color: #800000;"&gt;"""</span><span style="color: #000000;"&gt; request.user </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;执行request的user,这是的request已经是加工后的request了</span></pre>

c、那么我们可以从视图里面导入一下Request,找到request对象的user方法

rest_framework.views Request

hasattr(self, self._user

d、执行self._authenticate() 开始用户认证,如果验证成功后返回元组: (用户,用户Token)

authenticator user_auth_tuple =
        <span style="color: #0000ff;"&gt;if</span> user_auth_tuple <span style="color: #0000ff;"&gt;is</span> <span style="color: #0000ff;"&gt;not</span><span style="color: #000000;"&gt; None:
            self._authenticator </span>=<span style="color: #000000;"&gt; authenticator
            self.user,self.auth </span>= user_auth_tuple  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;返回一个元组,user,和auth,赋给了self,</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 只要实例化Request,就会有一个request对象,就可以request.user,request.auth了</span>
            <span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt;

    self._not_authenticated()</span></pre>

e、在user_auth_tuple = authenticator.authenticate(self) 进行验证,如果验证成功,执行类里的authenticatie方法

f、如果用户没有认证成功:self._not_authenticated()

Defaults are None,AnonymousUser &amp; None. </span><span style="color: #800000;"&gt;"""</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;如果跳过了所有认证,默认用户和Token和使用配置文件进行设置</span> self._authenticator = None <span style="color: #008000;"&gt;#


<span style="color: #0000ff;">if<span style="color: #000000;"> api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() <span style="color: #008000;">#<span style="color: #008000;"> 默认值为:匿名用户AnonymousUser
<span style="color: #0000ff;">else<span style="color: #000000;">:
self.user = None <span style="color: #008000;">#<span style="color: #008000;"> None 表示跳过该认证

    <span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; api_settings.UNAUTHENTICATED_TOKEN:
        self.auth </span>= api_settings.UNAUTHENTICATED_TOKEN()  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 默认值为:None</span>
    <span style="color: #0000ff;"&gt;else</span><span style="color: #000000;"&gt;:
        self.auth </span>=<span style="color: #000000;"&gt; None

</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; (user,token)</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 表示验证通过并设置用户名和Token;</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; AuthenticationFailed异常</span></pre>

三、完整过程

现在我们主要去分析rest_framework内部对这个url的具体实现过程。

    1. 首先我们访问http://127.0.0.1:8000/user/ 根据urls.py中的配置,执行views.TestView.as_view()函数
    2. as_view方法是被定义在rest_framework/views.py里面的一个静态方法,所以可以通过类名直接调用。

    3. 父类的as_view方法是定义在django/views/generic/base.py里面的View类中的方法。在这个方法中最终会执行cls.dispatch,在第一步中我们知道cls是

    4. dispatch是定义在TestView继承的父类APIView(rest_framework/views.py)里面的方法。在这个方法里面,首先通过request = self.initialize_request(request,**kwargs)这条语句重新封装了request对象

    5. initialize_request是APIView类里面的一个方法,重新封装了request对象,增加了一些属性信息

    6. 认证信息。主要通过APIView类中的get_authenticators(rest_framework/views.py)方法获取,这个方法会返回一个所有认证对象的列表
      在全局定义的authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

    7. 默认的认证配置信息是在rest_framework/settings.py文件中定义的

    8. 在rest_framework/authentication.py中定义了几种认证类型,一般情况我们需要自定义认证类,也可以使用django-oauth-toolkit组件进行认证。

    9. dispatch中的initialize_request方法执行完成之后,还有执行一个重要方法是self.initial(request,**kwargs),这个方法也是APIView类里的。在这个方法里面初始化
      被重新封装的request对象
      实现功能:
      • 版本处理
      • 用户认证
      • 权限
      • 访问频率限制

    10. 执行APIView里面的perform_authentication方法,该方法返回request.user,则会调用


    11. 执行rest_framework.request.Request类中的_authenticate方法,这个方法会遍历认证类,并根据认证结果给self.user,self.auth赋值。由于user,和auth都有property属性,
      所以给赋值的时候先在先执行setter方法


    12. dispatch中的initial方法执行完之后,会继续判断request.method并执行method相应的method.

    13. 执行TestView中定义的get方法,返回数据

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读