*Django authentication system*
1、 Django default user authentication system
Django authentication provides a user authentication system with two functions of authentication and authorization: the storage table auth uses_ user
For reference, click here
Django user authentication system deals with user accounts, groups, permissions and cookie based user sessions.
- Django authentication system handles both authentication and authorization
- Authentication: to verify whether a user can be used for account login.
- Authorization: authorization determines what an authenticated user is allowed to do.
- Django authentication system includes the following contents:
- User: user model class, user authentication.
- Permissions: identify whether a user can do a specific task.
- Group: unified management of multiple users with the same permissions.
- Password: a configurable password hash system, setting password and password verification.
from django.contrib import auth //Contains the core of the authentication framework and its default modelfrom django.contrib import contenttypes //Is the Django content type system, which allows permissions to be associated with models you create.
from django.contrib import auth //Make sure that each of your Django models is created with four default permissions: add, modify, delete, and viewfrom django.contrib.auth.models import User //User objectfrom django.contrib.auth import authenticate //Authenticate authenticate userfrom django.contrib.auth.models import Group //A general method of classifying users
Permission Operation of user object:
django.contrib.auth . models.User ”Object has two many to many fields:
It can be done through
user_permissionsProperty to assign permissions to
user, or through
permissionsProperty assigned to
myuser.groups.set([group_list]) myuser.groups.add(group, group, ...) myuser.groups.remove(group, group, ...) myuser.groups.clear() myuser.user_permissions.set([permission_list]) myuser.user_permissions.add(permission, permission, ...) myuser.user_permissions.remove(permission, permission, ...) myuser.user_permissions.clear()
Let’s take a look at the basics
Several methods are mainly used
- create_ User create user
- Authenticate authentication login
- Login remembers the login status of the user
- Logout log out
- Is_ Authenticated determines whether the user is logged in
login_ Required decorator to determine whether the user is logged in
The main attributes of the user object are username, password, email, first_ name, last_ name
from django.contrib.auth.models import User user = User.objects.create_user('yym', '[email protected]', 'yympassword')
~Create super user directive Python manage.py createsuperuser –username=yym –email=[email protected] ~
from django.contrib.auth.models import User u = User.objects.get(username='yym') u.set_password('new password') u.save()
~Change password instruction Python manage.py changepasswordusername ~
authenticate()To authenticate the user. It uses
passwordAs a parameter, each authentication backend is checked. If the back-end validation is valid, a user object is returned. If the
PermissionDeniedError, will return
from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials
When installed_ Apps set django.contrib.auth It will ensure that each of your Django models is created with four default permissions: add, modify, delete, and view
from car.models import UseCar from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType #Create the rights to issue orders for the vehicle model content_type = ContentType.objects.get_for_model(UseCar) permission = Permission.objects.create( codename='can_publish', name='Can Publish Posts', content_type=content_type, )
The first time you need to get a permission check on a user object,
ModelBackendWill cache their permissions
from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.shortcuts import get_object_or_404 from car.models import UseCar def user_gains_perms(request, user_id): user = get_object_or_404(User, pk=user_id) # any permission check will cache the current set of permissions user.has_perm('car.change_usecar') content_type = ContentType.objects.get_for_model(UseCar) permission = Permission.objects.get( codename='change_usecar', content_type=content_type, ) user.user_permissions.add(permission) # Checking the cached permission set user.has_perm('car.change_usecar') # False # Request new instance of User # Be aware that user.refresh_from_db() won't clear the cache. user = get_object_or_404(User, pk=user_id) # Permission cache is repopulated from the database user.has_perm('car.change_usecar') # True ...
Django uses sessions and middleware to hook the authentication system to the request object
They are provided in every request
request.userProperty. If no user is currently logged in, this property will be set to
AnonymousUserOtherwise, it will be set to
is_authenticatedTo distinguish whether a user has been authenticated
is_anonymousTo distinguish between user and anonymoususer objects
if request.user.is_authenticated: user ... else: pass
If you want to attach the authenticated user to the current session, you will pass the
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) //verificationif user is not None: login(request, user) //Sign in# Redirect to a success page. ... else: # Return an 'invalid login' error message. ...
Delete the authenticated user from the current session
from django.contrib.auth import logout def logout_view(request): logout(request)
The following problems are often encountered in actual project development (these problems will be discussed in detail later)
- Since the default user can’t meet our needs in actual development, we usually inherit the user table to expand and pay attention to the password plaintext when creating users after the expansion.
- In reality, due to some shortcomings of session, token based authentication mechanism will be used in general projects.
- As for the server, it must store the sessions of all online users, which takes up a lot of resources (CPU, memory), and seriously affects the performance of the server
- The server is extended to cluster, but there is also the problem of distributed session
- Django’s built-in permission mechanism cannot meet the needs of the project, which will expand the permission setting
Schematic diagram of session mechanism:
Schematic diagram of token mechanism:
This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint