How to Add User Authentication in Django Framework

Django has a user authentication system which handles a wide range functions from user accounts and cookie-based user sessions to groups and permissions. Authentication is a mechanism that connects incoming requests with identifying credentials including where the request came from and which token it is signed with. The permission policies can then be used to permit or deny the request.

The Django authentication system deals with both authentication and authorization. Authentication confirms if the user is actually who they claim to be while authorization determines what the user who has already been authenticated is allowed to do. In most cases, the term authentication refers to both tasks. A Django authentication system is composed of the following:

  • A group of users
  • Set of permissions including binary Yes/No flags which determines if a user is allowed to perform a certain task
  • Groups labels and permissions for multiple users
  • A password hashing system
  • View tools and forms used to log in users or restrict access to specific content
  • A backend system

Unlike most web authentic systems, the Django authentication is generic with relatively fewer features. The system uses third party packages to provide solutions for common problems such as checking password strength, throttling login attempts, and authentication of third parties such as OAuth.

Installation of the authentication

Authentication support is provided as a contrib. module (django.contrib.auth). The required configuration is by default included in which is generated from the django-admin startproject section. In the INSTALLED APPS settings you’ll find these two items:

  • The django.contrib.auth which holds the authentication framework core and the default models
  • The django.contrib.contenttypes which is the system’s content type that allows permissions related to the models created.

In the MIDDLEWARE setting, you’ll find these two items:

  • SessionsMiddleware which handles request sessions
  • AuthenticationMiddleware which connects users with session requests

When you have these settings already in place, you only need to run the command migrate to create database tables you need for auth related tasks and permissions in the apps you’ve installed.

How to use the Django authentication system

The Django authentication system has been changing over time as it continues to evolve in order to serve numerous tasks, handle project needs, and implement secure passwords and permissions.

Django also supports a wide range of extension and customizations to handle different types of projects with different authentication needs. The authentication and authorization features in Django authentication are somewhat combined or coupled together.

User objects in Django

The Django authentication system relies heavily on user objects. These are basically the people or users interacting with your site. User objects handle issues such as restricting access to specific content, connecting content with its creator, and registering new user profiles among other things.

Django authentication framework has only one user class. The “superusers” and admin staff users are not a different user class but user objects with specific sets of attributes. Default users have the following primary attributes:

  • Username
  • First name
  • Last name
  • Password
  • Email address

For a more detailed reference, you can check the full API documentation

How to create users

You can create users directly via the included create_user( ) function by going to django.contrib.auth.models import user. For example User = User.objects.create_user ( ‘jane’, ‘’, ‘janepassword’ ).

Jane is now a user object already created and saved in the database. You can then proceed to make any necessary changes in attributes or other fields such as ‘user.lastname then save at ‘ ( ).

Alternatively, you can create users interactively from the Django admin if you have it already installed.

How to create superusers

You can create superusers straight from the createsuperuser command. To do this, go to ‘python createsuperuser — username = jane — email =’.

You’ll be required to provide a password. The user will be created once you enter the password. You’ll also be prompted for the values –username or –email if you’ve left them blank.

How to change passwords

The system’s user model does not store clear text or raw passwords but stores a hash instead. Check this link for more details about password management:

Avoid manipulating user password attributes directly but refer to the helper function while creating a user. You can however change the user password in several ways.

  • The first method is via the commande line changepassword *username*. If the command prompts you to change a user password, you’ll be required to enter the password twice. If both passwords match, the new one will take effect immediately. If you don’t provide the user, the system will try to change the password for the username which matches the user currently using the system.
  • A password can also be changed from the set_password ( ) function. You can simply do this from django.contrib.auth.models Import users. The u = user.objects.get (username=’jane’) then u.set_password (‘new password’) and save the new password from ( ).
  • You can change user password if you have already installed Django admin from the authentication system’s admin pages by referring to this link:
  • The system also provides forms and views that allow all users to change passwords whenever they want.

Keep in mind that when you change your password, the system will automatically log you out of all your active sessions.

How to authenticate users

To authenticate users, you can use the ‘authenticate ( )’ function to validate user credentials. The function uses credentials as keyword arguments and the username and password values for the default case to verify each case and return the user object if the given credentials are valid for the backend. When the credentials provided are not valid for the backend or if the specified backend responds with PermissionDenied, the system returns a None response.

When a request that has not been authenticated is denied, you’ll get an error code such as HTTP 401 Unauthorized or HTTP 403 Permission denied. It is therefore important to ensure that you have the right username and password values for each user you add to the system.

More by stevenn.hansen

Topics of interest

More Related Stories