您好,登錄后才能下訂單哦!
這篇文章主要介紹了django.contirb.auth認證的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
首先看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: # 匿名用戶
感謝你能夠認真閱讀完這篇文章,希望小編分享的“django.contirb.auth認證的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。