欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解django.contirb.auth-認(rèn)證

 更新時間:2018年07月16日 10:23:44   作者:Thinking--  
這篇文章主要介紹了詳解django.contirb.auth-認(rèn)證,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

首先看middleware的定義:

auth模塊有兩個middleware:AuthenticationMiddleware和SessionAuthenticationMiddleware。

AuthenticationMiddleware負(fù)責(zé)向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屬性,因?yàn)樗枰猻ession存儲用戶信息。

user屬性的添加,被延遲到了get_user()函數(shù)里。SimpleLazyObject是一種延遲的技術(shù)。

在來看SessionAuthenticationMiddleware的定義:

它負(fù)責(zé)session驗(yàn)證

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()函數(shù)的定義。

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屬性,用來作為緩存。

因?yàn)橛脩粽J(rèn)證需要查詢數(shù)據(jù)庫,得到用戶的信息,所以減少開銷是有必要的。

注意,這種緩存只針對同一個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()

首先它會假設(shè)客戶端和服務(wù)器已經(jīng)建立session機(jī)制了,這個session中的SESSION_KEY屬性,就是user的id號。

這個session的BACKEND_SESSION_KEY屬性,就是指定使用哪種后臺技術(shù)獲取用戶信息。最后使用backend.get_user()獲取到user。如果不滿足,就返回AnonymousUser對象。

從這個獲取user的過程,首先有個前提,就是客戶端與服務(wù)端得先建立session機(jī)制。那么這個session機(jī)制是怎么建立的呢?

這個session建立的過程在auth.login函數(shù)里:

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)

首先它會判斷是否存在與用戶認(rèn)證相關(guān)的session,如果有就清空數(shù)據(jù),如果沒有就新建。

然后再寫如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)
    # 轉(zhuǎn)到成功頁面
  else:    # 返回錯誤信息

一般提交通過POST方式提交,然后調(diào)用authenticate方法驗(yàn)證,成功后使用login創(chuàng)建session。

繼續(xù)看看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,通過調(diào)用backend的authenticate方法認(rèn)證。

注意它在后面更新了user的backend屬性,表明此用戶是使用哪種backend認(rèn)證方式。它的值會在login函數(shù)里,被存放在session的BACKEND_SESSION_KEY屬性里。

通過backend的authenticate方法返回的user,是沒有這個屬性的。

最后說下登錄以后auth的用法。上面展示了登錄時auth的用法,在登錄以后,就會建立session機(jī)制。所以直接獲取request的user屬性,就可以判斷用戶的信息和狀態(tài)。

def my_view(request):
  if request.user.is_authenticated():
    # 認(rèn)證的用戶
  else:  
    # 匿名用戶

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 淺談tensorflow與pytorch的相互轉(zhuǎn)換

    淺談tensorflow與pytorch的相互轉(zhuǎn)換

    本文主要介紹了簡單介紹一下tensorflow與pytorch的相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 一文搞懂Python中列表List和元組Tuple的使用

    一文搞懂Python中列表List和元組Tuple的使用

    列表List 和 元組Tuple 可以說是 Python 中最通用、最有用的數(shù)據(jù)類型。列表是動態(tài)的,而元組具有靜態(tài)特征。本文將通過示例詳細(xì)講解二者的使用方法,需要的可以參考一下
    2022-04-04
  • Python3基礎(chǔ)教程之遞歸函數(shù)簡單示例

    Python3基礎(chǔ)教程之遞歸函數(shù)簡單示例

    這篇文章主要給大家介紹了關(guān)于Python3基礎(chǔ)教程之遞歸函數(shù)簡單示例的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Python3具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • Python學(xué)習(xí)之日志模塊詳解

    Python學(xué)習(xí)之日志模塊詳解

    說到日志,我們完全可以想象為現(xiàn)實(shí)生活中的日記。日記是我們平時記錄我們生活中點(diǎn)點(diǎn)滴滴的一種方法,而日志我們可以認(rèn)為是 程序的日記 ,程序的日記是用來記錄程序的行為。本文將詳細(xì)介紹Python中的日志模塊(logging),需要的可以參考一下
    2022-03-03
  • python 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)次數(shù)并進(jìn)行排序的實(shí)例

    python 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)次數(shù)并進(jìn)行排序的實(shí)例

    今天小編就為大家分享一篇python 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)次數(shù)并進(jìn)行排序的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • Python Django框架防御CSRF攻擊的方法分析

    Python Django框架防御CSRF攻擊的方法分析

    這篇文章主要介紹了Python Django框架防御CSRF攻擊的方法,結(jié)合實(shí)例形式分析了Python Django框架防御CSRF攻擊的原理、配置方法與使用技巧,需要的朋友可以參考下
    2019-10-10
  • Python如何import文件夾下的文件(實(shí)現(xiàn)方法)

    Python如何import文件夾下的文件(實(shí)現(xiàn)方法)

    下面小編就為大家?guī)硪黄狿ython如何import文件夾下的文件(實(shí)現(xiàn)方法)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • Python函數(shù)可變參數(shù)定義及其參數(shù)傳遞方式實(shí)例詳解

    Python函數(shù)可變參數(shù)定義及其參數(shù)傳遞方式實(shí)例詳解

    這篇文章主要介紹了Python函數(shù)可變參數(shù)定義及其參數(shù)傳遞方式,以實(shí)例形式較為詳細(xì)的分析了Python函數(shù)參數(shù)的使用技巧,需要的朋友可以參考下
    2015-05-05
  • 用python中的matplotlib繪制方程圖像代碼

    用python中的matplotlib繪制方程圖像代碼

    今天小編就為大家分享一篇用python中的matplotlib繪制方程圖像代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • python3.6利用pyinstall打包py為exe的操作實(shí)例

    python3.6利用pyinstall打包py為exe的操作實(shí)例

    今天小編就為大家分享一篇python3.6利用pyinstall打包py為exe的操作實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10

最新評論