Sitemap

Django Authentication System

2 min readAug 4, 2024

--

Django’s authentication system is robust and extensible, providing mechanisms for user authentication, authorization, and session management. It includes features such as user registration, login, logout, password management, and permissions. Here is a detailed overview:

Key Components of Django’s Authentication System

  1. User Model
  2. Authentication Backends
  3. Logging in a User
  4. Logging out a User

1. User Model

The user model is the core of Django’s authentication system. By default, Django provides a User model that includes fields like username, password, email, first_name, and last_name. However, Django allows for custom user models if the default one does not meet your requirements.

Create a New Django App:

python manage.py startapp accounts

Default User Model:

from django.contrib.auth.models import User

Custom User Model:

Get Sachinwuds’s stories in your inbox

Join Medium for free to get updates from this writer.

To define a custom user model, you need to subclass AbstractBaseUser or AbstractUser:

# accounts/models.py

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)

return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractBaseUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

objects = CustomUserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']

def __str__(self):
return self.email

You must also update AUTH_USER_MODEL in your settings:

# settings.py

AUTH_USER_MODEL = 'yourapp.CustomUser'

2. Authentication Backends

Authentication backends are responsible for authenticating users. Django supports multiple authentication backends and checks them in order. The default backend is ModelBackend.

# settings.py

AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]

Custom Authentication Backend

To create a custom authentication backend, you need to define a class that implements the authenticate and get_user methods. Here's a basic example:

# myapp/auth_backends.py

from django.contrib.auth.models import User

class MyCustomBackend:
def authenticate(self, request, username=None, password=None):
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None

def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

You then need to add this custom backend to the AUTHENTICATION_BACKENDS setting:

# settings.py

AUTHENTICATION_BACKENDS = [
'myapp.auth_backends.MyCustomBackend',
'django.contrib.auth.backends.ModelBackend',
]

Django’s authentication system is highly customizable and provides all the necessary tools to handle user authentication, authorization, and session management. By leveraging these components, you can build secure and robust web applications.

3. Logging in a User

from django.contrib.auth import authenticate, login

user = authenticate(request, username='john', password='johnpassword')
if user is not None:
login(request, user)
# Redirect to a success page.
else:
# Return an 'invalid login' error message.

4. Logging out a User

from django.contrib.auth import logout

def logout_view(request):
logout(request)
# Redirect to a success page.

--

--

Sachinwuds
Sachinwuds

Written by Sachinwuds

Experienced Cloud Architect & Python Developer with 5+ years in Python, Django, AWS, and Azure. Passionate about MLOps and data science. LinkedIn