Django rest_framework 认证源码流程
一、请求到来后,都要先执行dispatch方法
dispatch根据请求方式的不同触发get/post/put/delete等方法
注意,APIView中的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进行加工(添加数据)
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 # 第三步、执行:get/post/put/delete函数
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
二、上面是大致步骤,下面我们来具体分析一下
1、对request进行加工(添加数据)
我们来看看request里面都添加了那些数据
a、首先 request = self.initialize_request(request, *args, **kwargs)点进去,会发现:在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(), #解析数据,默认的有三种方式,可点进去看
#self.get_authenticator优先找自己的,没有就找父类的
authenticators=self.get_authenticators(), #获取认证相关的所有类并实例化,传入request对象供Request使用
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
b、获取认证相关的类的具体 authenticators=self.get_authenticators(),
def get_authenticators(self):
"""
Instantiates and returns the list of authenticators that this view can use.
"""
#返回的是对象列表
return [auth() for auth in self.authentication_classes] #[SessionAuthentication,BaseAuthentication]
c、查看认证的类:self.authentication_classes
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES #默认的,如果自定制了会优先执行自定制的
d、接着走进api_settings
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS) #点击继承的DEFAULTS类
DEFAULTS = {
# Base API policies
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication', #这时候就找到了他默认认证的类了,可以导入看看
'rest_framework.authentication.BasicAuthentication'
),
e、导入了类看看类里面具体干了什么
from rest_framework.authentication import SessionAuthentication
from rest_framework.authentication import BaseAuthentication
f、看到里面有个authenticate方法和authenticate_header方法
class BaseAuthentication(object):
"""
All authentication classes should extend BaseAuthentication.
""" def authenticate(self, request):
"""
Authenticate the request and return a two-tuple of (user, token).
"""
raise NotImplementedError(".authenticate() must be overridden.") def authenticate_header(self, request):
"""
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.
"""
pass
具体处理认证,从headers里面能获取用户名和密码
class BasicAuthentication(BaseAuthentication):
"""
HTTP Basic authentication against username/password.
"""
www_authenticate_realm = 'api' def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'basic':
return None #返回none不处理。让下一个处理 if len(auth) == 1:
msg = _('Invalid basic header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid basic header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg) try:
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') #用partition切割,保留了分割项冒号
except (TypeError, UnicodeDecodeError, binascii.Error):
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
raise exceptions.AuthenticationFailed(msg) userid, password = auth_parts[0], auth_parts[2] # 返回用户和密码
return self.authenticate_credentials(userid, password, request) def authenticate_credentials(self, userid, password, request=None):
"""
Authenticate the userid and password against username and password
with optional request for context.
"""
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(request=request, **credentials) if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return (user, None) def authenticate_header(self, request):
return 'Basic realm="%s"' % self.www_authenticate_realm
g、当然restfulframework默认定义了两个类。我们也可以自定制类,自己有就用自己的了,自己没有就去找父类的了,但是里面必须实现authenticate方法,不然会报错。
2、进行以下操作(处理版权信息,认证,权限,访问频率限制)
- 处理版权信息
- 认证
- 权限
- 请求用户进行访问频率的限制
我们主要来看一下认证流程
认证流程:
a、首先 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.
#2.1 处理版本信息
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted
#2.2 认证
self.perform_authentication(request)
# 2.3 权限
self.check_permissions(request)
# 2.4 请求用户进行访问频率的限制
self.check_throttles(request)
b、我们先来看认证,self.perform_authentication(request) 具体干了什么,按住ctrl点击进去
def perform_authentication(self, request):
"""
Perform authentication on the incoming request. 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.
"""
request.user #执行request的user,这是的request已经是加工后的request了
c、那么我们可以从视图里面导入一下Request,找到request对象的user方法
from rest_framework.views import Request
@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate() #
return self._user #返回user
d、执行self._authenticate() 开始用户认证,如果验证成功后返回元组: (用户,用户Token)
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
#循环对象列表
for authenticator in self.authenticators:
try:
#执行每一个对象的authenticate 方法
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 #返回一个元组,user,和auth,赋给了self,
# 只要实例化Request,就会有一个request对象,就可以request.user,request.auth了
return self._not_authenticated()
e、在user_auth_tuple = authenticator.authenticate(self) 进行验证,如果验证成功,执行类里的authenticatie方法
f、如果用户没有认证成功:self._not_authenticated()
def _not_authenticated(self):
"""
Set authenticator, user & authtoken representing an unauthenticated request. Defaults are None, AnonymousUser & None.
"""
#如果跳过了所有认证,默认用户和Token和使用配置文件进行设置
self._authenticator = None # if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() # 默认值为:匿名用户AnonymousUser
else:
self.user = None # None 表示跳过该认证 if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN() # 默认值为:None
else:
self.auth = None # (user, token)
# 表示验证通过并设置用户名和Token;
# AuthenticationFailed异常
3、执行get/post/delete等方法
4、对返回结果在进行加工
三、完整过程
现在我们主要去分析rest_framework内部对这个url的具体实现过程。
- 首先我们访问http://127.0.0.1:8000/user/ 根据urls.py中的配置,执行views.TestView.as_view()函数
as_view方法是被定义在rest_framework/views.py里面的一个静态方法,所以可以通过类名直接调用。
父类的as_view方法是定义在django/views/generic/base.py里面的View类中的方法。在这个方法中最终会执行cls.dispatch,在第一步中我们知道cls是<class 'app01.views.TestView'>
dispatch是定义在TestView继承的父类APIView(rest_framework/views.py)里面的方法。在这个方法里面,首先通过
request = self.initialize_request(request, *args, **kwargs)
这条语句重新封装了request对象initialize_request是APIView类里面的一个方法,重新封装了request对象,增加了一些属性信息
认证信息。主要通过APIView类中的get_authenticators(rest_framework/views.py)方法获取,这个方法会返回一个所有认证对象的列表
在全局定义的authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
默认的认证配置信息是在rest_framework/settings.py文件中定义的
在rest_framework/authentication.py中定义了几种认证类型,一般情况我们需要自定义认证类,也可以使用django-oauth-toolkit组件进行认证。
- dispatch中的initialize_request方法执行完成之后,还有执行一个重要方法是self.initial(request, *args, **kwargs),这个方法也是APIView类里的。在这个方法里面初始化
被重新封装的request对象
实现功能:- 版本处理
- 用户认证
- 权限
- 访问频率限制
执行APIView里面的perform_authentication方法,该方法返回request.user,则会调用<rest_framework.request.request object="" at="" 0x10e80deb8="">里面的user方法。在user方法里面最终调用了Request类里面的_authenticate方法
执行rest_framework.request.Request类中的_authenticate方法,这个方法会遍历认证类,并根据认证结果给self.user, self.auth赋值。由于user,和auth都有property属性,
所以给赋值的时候先在先执行setter方法dispatch中的initial方法执行完之后,会继续判断request.method并执行method相应的method.
执行TestView中定义的get方法,返回数据
Django rest_framework 认证源码流程的更多相关文章
- Python之Django rest_Framework框架源码分析
#!/usr/bin/env python # -*- coding:utf-8 -*- from rest_framework.views import APIView from rest_fram ...
- Django生命周期 URL ----> CBV 源码解析-------------- 及rest_framework APIView 源码流程解析
一.一个请求来到Django 的生命周期 FBV 不讨论 CBV: 请求被代理转发到uwsgi: 开始Django的流程: 首先经过中间件process_request (session等) 然后 ...
- Django admin组件源码流程
admin 组件 Django 自带的用户后台组件 用于用户便携的操作 admin 组件核心 启动 注册 设计url 启动核心代码 每个app 通过 apps.py 扫描 admin.py 文件 并执 ...
- Django后端项目----restful framework 认证源码流程
一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...
- restful framework 认证源码流程
一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...
- Rest Framework 认证源码流程
一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...
- Django drf:序列化增删改查、局部与全局钩子源码流程、认证源码分析、执行流程
一.序列化类的增.删.改.查 用drf的序列化组件 -定义一个类继承class BookSerializer(serializers.Serializer): -写字段,如果不指定source ...
- Django rest framework源码分析(1)----认证
目录 Django rest framework(1)----认证 Django rest framework(2)----权限 Django rest framework(3)----节流 Djan ...
- Django rest framework 源码分析 (1)----认证
一.基础 django 2.0官方文档 https://docs.djangoproject.com/en/2.0/ 安装 pip3 install djangorestframework 假如我们想 ...
随机推荐
- 卷积神经网络CNN 手写数字识别
1. 知识点准备 在了解 CNN 网络神经之前有两个概念要理解,第一是二维图像上卷积的概念,第二是 pooling 的概念. a. 卷积 关于卷积的概念和细节可以参考这里,卷积运算有两个非常重要特性, ...
- ICLR 2016 - Workshop Track International Conference on Learning Representations 论文papers
ICLR 2016 - Workshop Track International Conference on Learning Representations May 2 - 4, 2016, Car ...
- nose的测试报告
有时候我们要让报告整洁美观点,以html展示测试结果,我们可以借助pip install nosehtmloutput插件输出html格式报告 from nose.plugins.plugintest ...
- mac的dns缓存查询和清除
1.清楚dns缓存 dscacheutil -flushcache 2.查询nslookup
- 使用HttpClient发送请求接收响应
1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...
- ChartView与LineSeries搭配实现曲线局部缩放功能
效果图: 上一篇文章实现的时候还不知道有QtChart这个模块......好好看了下资料就想做个例子实现一下这功能,比较了下代码量...恩,直接看代码: Rectangle { id: view_re ...
- Nginx安装及配置文件解释
安装nginx,还是在mac上面用brew比较方便. 首先,brew install nginx,提示改权限 sudo chown -R $(whoami) /usr/local 然后brew ins ...
- 84. Largest Rectangle in Histogram-hard
84. Largest Rectangle in Histogram 题目 Given n non-negative integers representing the histogram's bar ...
- HTML5/CSS3实现添加锁屏效果
锁屏效果,也就是将屏幕置于模态,不允许用户触发任何动作,只能解除锁定后才能继续使用,jQueryUI的dialog有模态对话框,这一点不难做到.那么,首先需要在页面中添加一个div层,用于做模态的层 ...
- 巧妙使用 CSS3 的褪色和动画效果制作消息提醒框
现代Web设计技术允许开发者快速实现大多数浏览器支持的动画.我想警告消息是很常见的,因为默认的JavaScript警告框的样式往往(与你自己设计的漂亮样式)很不协调很囧.这使开发者步入找出哪种解决方案 ...