Authentication is the process of identifying a user and checking whether the user is allowed to access an application.
Django provides a built-in authentication system that includes users, password management, login, logout, permissions, groups, and sessions.
Authentication means verifying the identity of a user.
For example, when a user enters a username and password, the application checks whether the credentials are valid.
Username
+
Password
↓
Authentication
↓
User Identified
Authentication and authorization are related but different concepts.
| Concept | Meaning |
|---|---|
| Authentication | Checks who the user is. |
| Authorization | Checks what the user is allowed to do. |
For example, logging in is authentication, while checking whether a user can access an admin page is authorization.
Django includes an authentication framework as part of its built-in functionality.
It provides features such as:
Django provides a built-in User model through its authentication system.
from django.contrib.auth.models import User
The User model provides commonly required account information such as username, password, email, and permission-related information.
Django's authentication functionality is provided by
django.contrib.auth.
The authentication application is normally included in
INSTALLED_APPS in a new Django project.
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
Django's authentication system uses database tables for users, groups, permissions, and related information.
Run migrations to create the required database tables:
python manage.py migrate
After migration, the authentication system can store its database data.
A superuser has all available permissions by default.
Create a superuser using:
python manage.py createsuperuser
Django will ask for information such as username, email, and password.
Django provides a user manager for creating users.
from django.contrib.auth.models import User
user = User.objects.create_user(
username="rahul",
email="rahul@example.com",
password="secret123"
)
Use create_user() rather than directly storing a raw password
on the User object.
Django does not normally store user passwords as plain text. Its authentication system uses password hashing.
user.set_password(
"newpassword"
)
user.save()
This is important when creating or changing passwords programmatically.
Django provides check_password() to verify a password against
the stored password hash.
if user.check_password(
"secret123"
):
print("Password is correct")
The application should not compare passwords by reading or storing raw password values.
The authenticate() function checks the supplied credentials
against configured authentication backends.
from django.contrib.auth import authenticate
user = authenticate(
username="rahul",
password="secret123"
)
if user is not None:
print("Authentication successful")
else:
print("Invalid credentials")
After successfully authenticating a user, the login() function
can associate the user with the current session.
from django.contrib.auth import login
login(
request,
user
)
The user can then be recognized as logged in during subsequent requests.
The logout() function removes the user's authentication
information from the current session.
from django.contrib.auth import logout
logout(request)
It is commonly used by logout views.
A simple login view can authenticate the submitted username and password.
from django.shortcuts import render
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == "POST":
username = request.POST.get(
"username"
)
password = request.POST.get(
"password"
)
user = authenticate(
request,
username=username,
password=password
)
if user is not None:
login(request, user)
return render(
request,
"login.html"
)
A basic login form can contain username and password fields.
<form method="post">
{% csrf_token %}
<input
type="text"
name="username"
placeholder="Username"
>
<input
type="password"
name="password"
placeholder="Password"
>
<button type="submit">
Login
</button>
</form>
Django provides request.user to access the user associated
with the current request.
def dashboard(request):
print(request.user)
If the user is authenticated, this represents the logged-in user.
The is_authenticated attribute can be used to check whether
the current user is authenticated.
if request.user.is_authenticated:
print("User is logged in")
else:
print("User is not logged in")
This is useful for controlling access to pages and displaying different content.
The login_required decorator can restrict a view to
authenticated users.
from django.contrib.auth.decorators import (
login_required
)
@login_required
def dashboard(request):
return render(
request,
"dashboard.html"
)
Unauthenticated users are redirected according to the configured login URL behavior.
You can configure the login page used by authentication redirects.
LOGIN_URL = "/login/"
This setting is commonly used with login_required.
Django includes a permission system for controlling what users can do.
Permissions can be associated with actions such as:
Permissions can be assigned to users or groups.
You can check whether a user has a particular permission.
if request.user.has_perm(
"students.view_student"
):
print("Permission granted")
The permission name normally follows the format:
app_label.permission_codename
Groups allow permissions to be assigned to multiple users together.
For example:
Administrators
Teachers
Students
Instead of assigning the same permissions to every user individually, you can assign permissions to a group and add users to that group.
A user's groups can be checked through the user's relationship with groups.
if request.user.groups.filter(
name="Teachers"
).exists():
print("Teacher user")
This can be useful when different users should see different features.
Django authentication works together with sessions to remember authenticated users between requests.
After:
login(request, user)
Django associates the authenticated user with the current session.
This allows later requests to access the user through
request.user.
Django provides built-in authentication views that can be included in a project.
from django.urls import include, path
urlpatterns = [
path(
"accounts/",
include(
"django.contrib.auth.urls"
)
),
]
This can provide standard routes for features such as login, logout, and password management when the corresponding templates are provided.
Django's authentication system includes password management features.
These features can be used instead of building password handling from scratch.
Django allows projects to use a custom user model when the application's requirements differ from the default User model.
A custom user model is commonly configured through:
AUTH_USER_MODEL = "accounts.User"
When using a custom user model, it is important to plan this choice early in a project because changing user-model relationships later can require additional migration work.
User opens login page
↓
User enters username/password
↓
POST request
↓
authenticate()
↓
Credentials valid?
↙ ↘
Yes No
↓ ↓
login() Show error
↓
Session created
↓
Protected page
↓
request.user
This is the basic flow used by many Django login systems.
authenticate() before login.login() without a successfully authenticated user.{% csrf_token %} in internal POST login forms.Django provides a complete authentication framework for managing users and access to applications.
authenticate() verifies supplied credentials.login() associates an authenticated user with the session.logout() ends the authenticated session.request.user provides the current user.is_authenticated checks authentication status.login_required protects views.authenticate() checks credentials.login() logs an authenticated user into the current session.logout() logs the current user out.request.user represents the current user.login_required can protect private views.Question: Which Django function is used to verify a user's credentials?