您好,登錄后才能下訂單哦!
這篇文章主要介紹了django.contirb.auth認(rèn)證的示例分析,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
首先看middleware的定義:
auth模塊有兩個(gè)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))
可以看見(jiàn)AuthenticationMiddleware首先檢查是否由session屬性,因?yàn)樗枰猻ession存儲(chǔ)用戶信息。
user屬性的添加,被延遲到了get_user()函數(shù)里。SimpleLazyObject是一種延遲的技術(shù)。
在來(lái)看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)
通過(guò)比較user的get_session_auth_hash方法,和session里面的auth.HASH_SESSION_KEY屬性,判斷用戶的session是否正確。
至于request里面的user對(duì)象,由有什么屬性,需要看看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屬性,用來(lái)作為緩存。
因?yàn)橛脩粽J(rèn)證需要查詢數(shù)據(jù)庫(kù),得到用戶的信息,所以減少開(kāi)銷(xiāo)是有必要的。
注意,這種緩存只針對(duì)同一個(gè)request而言的,即在一個(gè)view中多次訪問(wèn)request.user屬性。
每次http請(qǐng)求都是新的request。
再接著看auth.get_user()方法的定義,深入了解request.user這個(gè)對(duì)象:
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()
首先它會(huì)假設(shè)客戶端和服務(wù)器已經(jīng)建立session機(jī)制了,這個(gè)session中的SESSION_KEY屬性,就是user的id號(hào)。
這個(gè)session的BACKEND_SESSION_KEY屬性,就是指定使用哪種后臺(tái)技術(shù)獲取用戶信息。最后使用backend.get_user()獲取到user。如果不滿足,就返回AnonymousUser對(duì)象。
從這個(gè)獲取user的過(guò)程,首先有個(gè)前提,就是客戶端與服務(wù)端得先建立session機(jī)制。那么這個(gè)session機(jī)制是怎么建立的呢?
這個(gè)session建立的過(guò)程在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)
首先它會(huì)判斷是否存在與用戶認(rèn)證相關(guān)的session,如果有就清空數(shù)據(jù),如果沒(méi)有就新建。
然后再寫(xiě)如session的值:SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY。
然后講一下登錄時(shí),使用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)到成功頁(yè)面 else: # 返回錯(cuò)誤信息
一般提交通過(guò)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))
它會(huì)去輪詢backends,通過(guò)調(diào)用backend的authenticate方法認(rèn)證。
注意它在后面更新了user的backend屬性,表明此用戶是使用哪種backend認(rèn)證方式。它的值會(huì)在login函數(shù)里,被存放在session的BACKEND_SESSION_KEY屬性里。
通過(guò)backend的authenticate方法返回的user,是沒(méi)有這個(gè)屬性的。
最后說(shuō)下登錄以后auth的用法。上面展示了登錄時(shí)auth的用法,在登錄以后,就會(huì)建立session機(jī)制。所以直接獲取request的user屬性,就可以判斷用戶的信息和狀態(tài)。
def my_view(request): if request.user.is_authenticated(): # 認(rèn)證的用戶 else: # 匿名用戶
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“django.contirb.auth認(rèn)證的示例分析”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。