Basic process principle of Python Django 02 authentication system


*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.

Main modules:

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.

Module details:

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:groupsanduser_permissions

It can be done throughuser_permissionsProperty to assign permissions touser, or throughpermissionsProperty assigned togroup


myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)

Let’s take a look at the basics

2、 Implementation of user authentication system

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

1. Create user:

The main attributes of the user object are username, password, email, first_ name, last_ name

1.1 common create user

from django.contrib.auth.models import User
user = User.objects.create_user('yym', '[email protected]', 'yympassword')

~Create super user directive Python createsuperuser –username=yym –email=[email protected] ~

1.2 change password

    from django.contrib.auth.models import User
    u = User.objects.get(username='yym')
    u.set_password('new password')

~Change password instruction Python changepasswordusername ~

2. Verify users

useauthenticate()To authenticate the user. It usesusernameandpasswordAs a parameter, each authentication backend is checked. If the back-end validation is valid, a user object is returned. If thePermissionDeniedError, will returnNone

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
    # A backend authenticated the credentials
    # No backend authenticated the credentials

3. Authority

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

3.1 create permissions

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(
    name='Can Publish Posts',

3.2 permission cache

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

    content_type = ContentType.objects.get_for_model(UseCar)
    permission = Permission.objects.get(

    # 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


4. Authentication of web request

4.1 verification of web requests

Django uses sessions and middleware to hook the authentication system to the request object

They are provided in every requestrequest.userProperty. If no user is currently logged in, this property will be set toAnonymousUserOtherwise, it will be set toUserexample.

useuserProperties ofis_authenticatedTo distinguish whether a user has been authenticated

useuserProperties ofis_anonymousTo distinguish between user and anonymoususer objects

if request.user.is_authenticated:

4.2 user login

If you want to attach the authenticated user to the current session, you will pass thelogin()Function completion

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.
        # Return an 'invalid login' error message.

4.3 user logout

Delete the authenticated user from the current sessionlogout()Function completion

from django.contrib.auth import logout

def logout_view(request):

The following problems are often encountered in actual project development (these problems will be discussed in detail later)

  1. 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.
  1. In reality, due to some shortcomings of session, token based authentication mechanism will be used in general projects.
    1. 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
    2. The server is extended to cluster, but there is also the problem of distributed session
  1. Django’s built-in permission mechanism cannot meet the needs of the project, which will expand the permission setting

Schematic diagram of session mechanism:

Basic process principle of Python Django 02 authentication system

Schematic diagram of token mechanism:

Basic process principle of Python Django 02 authentication system

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint