详解django.contirb.auth-认证

yipeiwu_com5年前Python基础

首先看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设计】。

相关文章

利用Psyco提升Python运行速度

Psyco 是严格地在 Python 运行时进行操作的。也就是说,Python 源代码是通过 python 命令编译成字节码的,所用的方式和以前完全相同(除了为调用 Psyco 而添加的...

python使用筛选法计算小于给定数字的所有素数

本文实例为大家分享了python计算小于给定数字的所有素数的具体代码,供大家参考,具体内容如下 代码思路:首先列出指定范围内所有候选数字,然后从前往后依次选择一个数字去除以后面所有数字,...

selenium 多窗口切换的实现(windows)

在web应用中,常常会遇见点击某个链接会弹出一个新的窗口,或者是相互关联的web应用 ,这样要去操作新窗口中的元素,这时就需要主机切换到新窗口进行操作。。WebDriver 提供了swi...

Python当中的array数组对象实例详解

Python当中的array数组对象实例详解

计算机为数组分配一段连续的内存,从而支持对数组随机访问; 由于项的地址在编号上是连续的,数组某一项的地址可以通过将两个值相加得出,即将数组的基本地址和项的偏移地址相加。 数组的基本地址...

python文件比较示例分享

复制代码 代码如下:# 比较两个字符串,如果不同返回第一个不相同的位置# 如果相同返回0def cmpstr(str1, str2):    col = 0...