"""
Provides various authentication policies.
"""
import base64
import binascii # 后续讲解如下包
from django.contrib.auth import authenticate, get_user_model
from django.middleware.csrf import CsrfViewMiddleware
from django.utils.translation import gettext_lazy as _ from rest_framework import HTTP_HEADER_ENCODING, exceptions # 获取请求头
def get_authorization_header(request):
"""
Return request's 'Authorization:' header, as a bytestring.
以字符串的形式返回请求的Authorization Hide some test client ickyness where the header can be unicode.
"""
auth = request.META.get('HTTP_AUTHORIZATION', b'')
# 获取请求头中的AUTHORIZATION
if isinstance(auth, str):
# 判断auth是否为字符串类型
# Work around django test client oddness
auth = auth.encode(HTTP_HEADER_ENCODING)
#
return auth class CSRFCheck(CsrfViewMiddleware):
def _reject(self, request, reason):
# Return the failure reason instead of an HttpResponse
return reason # 基类
class BaseAuthentication:
"""
All authentication classes should extend BaseAuthentication.
认证,必须重写authenticate
""" 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 # 返回用户user,基于用户名密码验证
class BasicAuthentication(BaseAuthentication):
"""
HTTP Basic authentication against username/password.
针对用户名/密码的HTTP基本身份验证。
"""
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`.
如果提供了正确的用户名和密码,则返回“用户”。 否则返回“None”。
"""
auth = get_authorization_header(request).split()
# 获取请求头传入的参数,并以空格切割 if not auth or auth[0].lower() != b'basic':
# 判断是否接受到,长度为2
return 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:
# 对请求头解码,获取用户ID和密码
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).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 # session,经过csrf
class SessionAuthentication(BaseAuthentication):
"""
Use Django's session framework for authentication.
""" def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None`.
""" # Get the session-based user from the underlying HttpRequest object
# 调用Django request,
user = getattr(request._request, 'user', None) # Unauthenticated, CSRF validation not required
if not user or not user.is_active:
return None self.enforce_csrf(request) # CSRF passed with authenticated user
return (user, None)
# 经过中间件验证,复杂,前后端分离基本不用,有空分析
def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
check = CSRFCheck()
# populates request.META['CSRF_COOKIE'], which is used in process_view()
check.process_request(request)
reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) # token验证
class TokenAuthentication(BaseAuthentication):
"""
Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization"
HTTP header, prepended with the string "Token ". For example:
客户应通过在“授权”中传递令牌密钥进行身份验证
HTTP标头,以字符串“ Token”开头。
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
""" keyword = 'Token'
model = None def get_model(self):
if self.model is not None:
return self.model
from rest_framework.authtoken.models import Token
return Token """
A custom token model may be used, but must have the following properties. * key -- The string identifying the token
* user -- The user to which the token belongs
"""
# 上述相同
def authenticate(self, request):
auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode():
return None if len(auth) == 1:
msg = _('Invalid token header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid token header. Token string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg) try:
token = auth[1].decode()
except UnicodeError:
msg = _('Invalid token header. Token string should not contain invalid characters.')
raise exceptions.AuthenticationFailed(msg) return self.authenticate_credentials(token) def authenticate_credentials(self, key):
model = self.get_model()
try:
# 获取token值,model为token表获取到的token模型
# model.objects.get类似,'user'传入的字段,
token = model.objects.select_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed(_('Invalid token.')) if not token.user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
# 返回
return (token.user, token) def authenticate_header(self, request):
return self.keyword # 远程验证
class RemoteUserAuthentication(BaseAuthentication):
"""
REMOTE_USER authentication. To use this, set up your web server to perform authentication, which will
set the REMOTE_USER environment variable. You will need to have
'django.contrib.auth.backends.RemoteUserBackend in your
AUTHENTICATION_BACKENDS setting
远程验证,如果需要,则setting配置AUTHENTICATION_BACKENDS,
调用代码:
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
""" # Name of request header to grab username from. This will be the key as
# used in the request.META dictionary, i.e. the normalization of headers to
# all uppercase and the addition of "HTTP_" prefix apply.
header = "REMOTE_USER" def authenticate(self, request):
user = authenticate(remote_user=request.META.get(self.header))
if user and user.is_active:
return (user, None)

解读 authentication.py的更多相关文章

  1. keras系列︱Application中五款已训练模型、VGG16框架(Sequential式、Model式)解读(二)

    引自:http://blog.csdn.net/sinat_26917383/article/details/72859145 中文文档:http://keras-cn.readthedocs.io/ ...

  2. REST、DRF(View源码解读、APIView源码解读)

    一 . REST            前言 1 . 编程 : 数据结构和算法的结合 .小程序如简单的计算器,我们输入初始数据,经过计算,得到最终的数据,这个过程中,初始数据和结果数据都是数据,而计算 ...

  3. Restful 1 -- REST、DRF(View源码解读、APIView源码解读)及框架实现

    一.REST 1.什么是编程? 数据结构和算法的结合 2.什么是REST? - url用来唯一定位资源,http请求方式来区分用户行为 首先回顾我们曾经做过的图书管理系统,我们是这样设计url的,如下 ...

  4. 《Django By Example》第四章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:祝大家新年快乐,这次带来<D ...

  5. Python开发程序:ATM+购物商城

    一.程序要求 模拟实现一个ATM + 购物商城程序 额度 15000或自定义 实现购物商城,买东西加入 购物车,调用信用卡接口结账 可以提现,手续费5% 每月22号出账单,每月10号为还款日,过期未还 ...

  6. restful framework 认证源码流程

    一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...

  7. Flask 学习 十三 应用编程接口

    最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. REST的六个特性: 客户端-服务器(Client-Server)服务器 ...

  8. drf相关问题

    drf自定义用户认证: 登录默认 使用django的ModelBackend,对用户名和密码进行验证.但我们平时登录网站时除了用户名也可以用邮箱或手机进行登录,这就需要我们自己扩展backend 一. ...

  9. python-nmap的函数学习

    简介 python-nmap是一个使用nmap进行端口扫描的python库,它可以很轻易的生成nmap扫描报告,并且可以帮助系统管理员进行自动化扫描任务和生成报告.同时,它也支持nmap脚本输出. 可 ...

随机推荐

  1. LeetCode 热题 HOT 100(05,正则表达式匹配)

    LeetCode 热题 HOT 100(05,正则表达式匹配) 不够优秀,发量尚多,千锤百炼,方可成佛. 算法的重要性不言而喻,无论你是研究者,还是最近比较火热的IT 打工人,都理应需要一定的算法能力 ...

  2. JavaScript中.、[]与setAttribute()在设置属性上的区别

    .和[] javaScript.和[]既可以对所有js对象设置属性,但是对于DOM对象它设置的属性有些特殊.对于元素DOM标准属性,实现属性值的设置/更改;对于元素DOM非标准属性,仅在js中有效,在 ...

  3. fork函数拓展

    1.fork之后父子进程共享文件:文件引用计数的值改变,共享偏移. 在下面的例子中test.txt为parentchil.如果子进程没有睡眠,两个进程交叉执行,内容不可预测. 1 #include&l ...

  4. charles技能之修改请求参数/返回数据(map Local、Rewrite、Breakpoints)

    之前一直用postman调接口比较多,但有时候想要去修改APP的页面展示,造数据又会比较麻烦,此时可以用以下三种方法修改请求参数或修改响应: map Local(本地映射).Breakpoints(打 ...

  5. switch,case语句易误区

    switch case 语句语法格式如下: switch(expression){ case value : //语句 break; //可选 case value : //语句 break; //可 ...

  6. 4.Spring Boot web开发

    1.创建一个web模块 (1).创建SpringBoot应用,选中我们需要的模块: (2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来 (3).自己编 ...

  7. [原题复现][极客大挑战 2019]BuyFlag

    简介  原题复现:[极客大挑战 2019]BuyFlag  考察知识点:php函数特性(is_numeric().strcmp函数())  线上平台:https://buuoj.cn(北京联合大学公开 ...

  8. 阿里技术专家深入讲解,SpringMVC入门到进阶,看这一篇就够了

    前言 SpringMVC是一个实现了Web MVC设计模式的轻量级Web框架.它与前辈Struts 2框架一样,都属于MVC框架,因为其使用和性能等方面比Struts 2更加优异,所以Spring M ...

  9. FL studio系列教程(十六):FL Studio查看菜单讲解

    FL Studio中每个窗口的显示.隐藏和布局命令都在查看菜单中.其中它被分为窗口.布局和浏览器3个部分,各项名称都有其单独的作用.窗口部分主要是软件的显示的一些菜单这里就不详细讲解了,接下来我们重点 ...

  10. 利用perspective 和 transform 里面的几个参数来实现旋转照片墙

    旋转照片墙 首先,来看下,是什么效果吧,上效果图 ↓ 其实这个东西,很容易制作,先说下思路, 把照片都给叠在一起,然后 rotateY 旋转,给每张图片 旋转不一样的角度能构成一圈, 然后transl ...