Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of django.contirb.auth Authentication

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of django.contirb.auth certification, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

First, look at the definition of middleware:

The auth module has two middleware:AuthenticationMiddleware and SessionAuthenticationMiddleware.

AuthenticationMiddleware is responsible for adding user attributes to request

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))

You can see that AuthenticationMiddleware first checks to see if the session attribute is used, because it requires session to store user information.

The addition of the user attribute is delayed to the get_user () function. SimpleLazyObject is a latency technology.

Let's look at the definition of SessionAuthenticationMiddleware:

It is responsible for session verification

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)

Compare the get_session_auth_hash method of user with the auth.HASH_SESSION_KEY attribute in session to determine whether the user's session is correct.

As for the user object in request, what attributes you have, you need to look at the definition of the get_user () function.

Def get_user (request): if not hasattr (request,'_ cached_user'): request._cached_user = auth.get_user (request) return request._cached_user

Obviously, the get_user method adds the _ cached_user attribute to the request, which is used as a cache.

Because user authentication needs to query the database and get the user's information, it is necessary to reduce the overhead.

Note that this cache is only for the same request, that is, accessing the request.user property multiple times in a view.

Each http request is a new request.

Then take a look at the definition of the auth.get_user () method to learn more about the object 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 `AnatomousUser` is returned." From .models import AnonymousUser user = None try: user_id = request. Session [session _ KEY] backend_path = request. Session [backup _ 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 ()

First of all, it assumes that the client and server have established the session mechanism, and the SESSION_KEY attribute in this session is the id number of the user.

The BACKEND_SESSION_KEY attribute of this session specifies which background technology to use to obtain user information. Finally, use backend.get_user () to get the user. If not, the AnonymousUser object is returned.

First of all, there is a premise in the process of obtaining user from this, that is, the client and server have to establish the session mechanism first. So how is this session mechanism established?

The process of establishing the session is in the auth.login function:

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 [backup _ SESSION_KEY] = user.backend request. Session [hash _ SESSION_KEY] = session_auth_hash if hasattr (request, 'user'): request.user = user rotate_token (request)

First of all, it will determine whether there is a session related to user authentication, if so, empty the data, and if not, create a new one.

Then write values such as session: SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY.

Then let's talk about the usual practice of using auth when logging in:

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) # go to the success page else: # return error message

Generally, the submission is submitted through POST, and then the authenticate method is called for verification. After success, the session is created using login.

Move on to the definition of 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))

It polls the backends and authenticates it by calling the authenticate method of backend.

Notice that it updates the backend property of user later, indicating which backend authentication method this user is using. Its value will be stored in the login function and in the BACKEND_SESSION_KEY property of session.

The user returned through the authenticate method of backend does not have this attribute.

Finally, let's talk about the use of auth after login. The above shows the use of auth when logging in, and after logging in, the session mechanism is established. So if you get the user attribute of request directly, you can judge the information and status of the user.

Def my_view (request): if request.user.is_authenticated (): # authenticated user else: # Anonymous user Thank you for reading this article carefully. I hope the article "sample Analysis of django.contirb.auth Certification" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report