详解django.contirb.auth-认证


Posted in Python onJuly 16, 2018

首先看middleware的定义:

auth模块有两个middleware:AuthenticationMiddleware和SessionAuthenticationMiddleware。

AuthenticationMiddleware负责向request添加user属性

class AuthenticationMiddleware(object):
  def process_request(self, request):
    assert hasattr(request, 'session'), (
      "The Django authentication middleware requires session middleware "
      "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
      "'django.contrib.sessions.middleware.SessionMiddleware' before "
      "'django.contrib.auth.middleware.AuthenticationMiddleware'."
    )
    request.user = SimpleLazyObject(lambda: get_user(request))

可以看见AuthenticationMiddleware首先检查是否由session属性,因为它需要session存储用户信息。

user属性的添加,被延迟到了get_user()函数里。SimpleLazyObject是一种延迟的技术。

在来看SessionAuthenticationMiddleware的定义:

它负责session验证

class SessionAuthenticationMiddleware(object):
  """
  Middleware for invalidating a user's sessions that don't correspond to the
  user's current session authentication hash (generated based on the user's
  password for AbstractUser).
  """
  def process_request(self, request):
    user = request.user
    if user and hasattr(user, 'get_session_auth_hash'):
      session_hash = request.session.get(auth.HASH_SESSION_KEY)
      session_hash_verified = session_hash and constant_time_compare(
        session_hash,
        user.get_session_auth_hash()
      )
      if not session_hash_verified:
        auth.logout(request)

通过比较user的get_session_auth_hash方法,和session里面的auth.HASH_SESSION_KEY属性,判断用户的session是否正确。

至于request里面的user对象,由有什么属性,需要看看get_user()函数的定义。

def get_user(request):
  if not hasattr(request, '_cached_user'):
    request._cached_user = auth.get_user(request)
  return request._cached_user

显然get_user方法在request增加了_cached_user属性,用来作为缓存。

因为用户认证需要查询数据库,得到用户的信息,所以减少开销是有必要的。

注意,这种缓存只针对同一个request而言的,即在一个view中多次访问request.user属性。

每次http请求都是新的request。

再接着看auth.get_user()方法的定义,深入了解request.user这个对象:

def get_user(request):
  """
  Returns the user model instance associated with the given request session.
  If no user is retrieved an instance of `AnonymousUser` is returned.
  """
  from .models import AnonymousUser
  user = None
  try:
    user_id = request.session[SESSION_KEY]
    backend_path = request.session[BACKEND_SESSION_KEY]
  except KeyError:
    pass
  else:
    if backend_path in settings.AUTHENTICATION_BACKENDS:
      backend = load_backend(backend_path)
      user = backend.get_user(user_id)
  return user or AnonymousUser()

首先它会假设客户端和服务器已经建立session机制了,这个session中的SESSION_KEY属性,就是user的id号。

这个session的BACKEND_SESSION_KEY属性,就是指定使用哪种后台技术获取用户信息。最后使用backend.get_user()获取到user。如果不满足,就返回AnonymousUser对象。

从这个获取user的过程,首先有个前提,就是客户端与服务端得先建立session机制。那么这个session机制是怎么建立的呢?

这个session建立的过程在auth.login函数里:

def login(request, user):
  """
  Persist a user id and a backend in the request. This way a user doesn't
  have to reauthenticate on every request. Note that data set during
  the anonymous session is retained when the user logs in.
  """
  session_auth_hash = ''
  if user is None:
    user = request.user
  if hasattr(user, 'get_session_auth_hash'):
    session_auth_hash = user.get_session_auth_hash()

  if SESSION_KEY in request.session:
    if request.session[SESSION_KEY] != user.pk or (
        session_auth_hash and
        request.session.get(HASH_SESSION_KEY) != session_auth_hash):
      # To avoid reusing another user's session, create a new, empty
      # session if the existing session corresponds to a different
      # authenticated user.
      request.session.flush()
  else:
    request.session.cycle_key()
  request.session[SESSION_KEY] = user.pk
  request.session[BACKEND_SESSION_KEY] = user.backend
  request.session[HASH_SESSION_KEY] = session_auth_hash
  if hasattr(request, 'user'):
    request.user = user
  rotate_token(request)

首先它会判断是否存在与用户认证相关的session,如果有就清空数据,如果没有就新建。

然后再写如session的值:SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY。

然后讲一下登录时,使用auth通常的做法:

from django.contrib.auth import authenticate, login 
def login_view(request):
  username = request.POST['username']
  password = request.POST['password']
  user = authenticate(username=username, password=password)
  if user is not None:
    login(request, user)
    # 转到成功页面
  else:    # 返回错误信息

一般提交通过POST方式提交,然后调用authenticate方法验证,成功后使用login创建session。

继续看看authenticate的定义:

def authenticate(**credentials):
  """
  If the given credentials are valid, return a User object.
  """
  for backend in get_backends():
    try:
      inspect.getcallargs(backend.authenticate, **credentials)
    except TypeError:
      # This backend doesn't accept these credentials as arguments. Try the next one.
      continue

    try:
      user = backend.authenticate(**credentials)
    except PermissionDenied:
      # This backend says to stop in our tracks - this user should not be allowed in at all.
      return None
    if user is None:
      continue
    # Annotate the user object with the path of the backend.
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    return user

  # The credentials supplied are invalid to all backends, fire signal
  user_login_failed.send(sender=__name__,
      credentials=_clean_credentials(credentials))

它会去轮询backends,通过调用backend的authenticate方法认证。

注意它在后面更新了user的backend属性,表明此用户是使用哪种backend认证方式。它的值会在login函数里,被存放在session的BACKEND_SESSION_KEY属性里。

通过backend的authenticate方法返回的user,是没有这个属性的。

最后说下登录以后auth的用法。上面展示了登录时auth的用法,在登录以后,就会建立session机制。所以直接获取request的user属性,就可以判断用户的信息和状态。

def my_view(request):
  if request.user.is_authenticated():
    # 认证的用户
  else:  
    # 匿名用户

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现在matplotlib中两个坐标轴之间画一条直线光标的方法
May 20 Python
Python提取Linux内核源代码的目录结构实现方法
Jun 24 Python
Zabbix实现微信报警功能
Oct 09 Python
python扫描proxy并获取可用代理ip的实例
Aug 07 Python
Python实现繁?转为简体的方法示例
Dec 18 Python
python打开windows应用程序的实例
Jun 28 Python
pandas计算最大连续间隔的方法
Jul 04 Python
python GUI库图形界面开发之PyQt5窗口布局控件QStackedWidget详细使用方法
Feb 27 Python
python3通过udp实现组播数据的发送和接收操作
May 05 Python
浅谈Python 命令行参数argparse写入图片路径操作
Jul 12 Python
Python request中文乱码问题解决方案
Sep 17 Python
浅谈Python类的单继承相关知识
May 12 Python
Python爬虫使用脚本登录Github并查看信息
Jul 16 #Python
django认证系统实现自定义权限管理的方法
Jul 16 #Python
Sanic框架路由用法实例分析
Jul 16 #Python
Sanic框架安装与简单入门示例
Jul 16 #Python
python 除法保留两位小数点的方法
Jul 16 #Python
Python自定义装饰器原理与用法实例分析
Jul 16 #Python
python 正确保留多位小数的实例
Jul 16 #Python
You might like
PHP支持多种格式图片上传(支持jpg、png、gif)
2011/11/03 PHP
PHP 正则表达式小结
2015/02/12 PHP
smarty模板判断数组为空的方法
2015/06/10 PHP
PHP使用缓存即时输出内容(output buffering)的方法
2015/08/03 PHP
php实时倒计时功能实现方法详解
2017/02/27 PHP
form自动提交实例讲解
2017/07/10 PHP
Jquery实现弹出层分享微博插件具备动画效果
2013/04/03 Javascript
jquery实现select下拉框美化特效代码分享
2015/08/18 Javascript
JavaScript基础篇(6)之函数表达式闭包
2015/12/11 Javascript
炫酷的js手风琴效果
2016/10/13 Javascript
Node.js连接postgreSQL并进行数据操作
2016/12/18 Javascript
React + webpack 环境配置的方法步骤
2017/09/07 Javascript
vue轮播图插件vue-concise-slider的使用
2018/03/13 Javascript
在vue中安装使用vux的教程详解
2018/09/16 Javascript
vue通信方式EventBus的实现代码详解
2019/06/10 Javascript
uni-app使用微信小程序云函数的步骤示例
2020/05/22 Javascript
python list中append()与extend()用法分享
2013/03/24 Python
python通过pil模块获得图片exif信息的方法
2015/03/16 Python
详解Python程序与服务器连接的WSGI接口
2015/04/29 Python
Python按行读取文件的实现方法【小文件和大文件读取】
2016/09/19 Python
python 读写文件,按行修改文件的方法
2018/07/12 Python
pytorch 使用加载训练好的模型做inference
2020/02/20 Python
使paramiko库执行命令时在给定的时间强制退出功能的实现
2021/03/03 Python
Myholidays美国:在线旅游网站
2019/08/16 全球购物
高中的职业生涯规划书
2013/12/28 职场文书
校本教研工作制度
2014/01/22 职场文书
小学中秋节活动方案
2014/02/06 职场文书
财务信息服务专业自荐书范文
2014/02/08 职场文书
请假条的格式
2014/04/11 职场文书
低碳生活倡议书
2014/04/14 职场文书
数控技校生自我鉴定
2014/04/19 职场文书
学习党的群众路线对照检查材料
2014/09/29 职场文书
局机关干部群众路线个人对照检查材料思想汇报
2014/10/05 职场文书
送给火锅店的创意营销方案!
2019/07/08 职场文书
element多个表单校验的实现
2021/05/27 Javascript
nginx日志格式分析和修改
2022/04/28 Servers