Learn Django Β· 9/13

Authentication: Securing Your App πŸ”

7 min read

Course: Django

Topic 9: Authentication: Securing Your App πŸ”

Authentication is the process of verifying the identity of a user or system. Authorization is the process of verifying what specific applications, files, and data a user has access to.

The Problem: By default, web applications are completely open. Any user can access any URL, submit any form, and view any data. If you are building a social network, an e-commerce platform, or a private dashboard, you need to know who is making the request so you can show them their own data and protect sensitive areas.

The Solution: Django comes with a fully-featured, built-in authentication system (django.contrib.auth). It handles user accounts, groups, permissions, and cookie-based user sessions.

Imagine you are managing an exclusive corporate office. Authentication is the front desk checking your ID card to prove you are an employee. Authorization is the internal security system that allows your card to open the cafeteria door, but triggers an alarm if you try to swipe into the CEO's private safe.

Let's learn how to secure your Django application.


1. The Built-in User Model: Registration, Login, and Logout

The Problem: Handling user passwords manually is a massive security risk. If you store passwords as plain text in your database, a single data breach exposes all your users. Writing your own cryptographic hashing, session management, and brute-force protection is generally a terrible idea unless you are a cryptography engineer. (It is commonly said in the industry: Writing your own crypto is like trying to build a parachute while you are already falling.)

The Solution: Django provides a built-in User model, form validations (UserCreationForm), and authentication views out of the box. Under the hood, Django uses the PBKDF2 algorithm with a SHA256 hash to safely store passwords.

Setting up Login and Logout

Instead of writing views to check passwords, we use Django's built-in Class-Based Views (CBVs) for logging in and out.

In your urls.py, you can include the default authentication URLs:

python
# urls.py
from django.urls import path, include

urlpatterns = [
    # This single line gives you login, logout, password reset, etc.
    path('accounts/', include('django.contrib.auth.urls')),
]

By adding that line, Django automatically creates routes for:

  • /accounts/login/
  • /accounts/logout/
  • /accounts/password_change/
  • (and a few others)

You only need to create the HTML template for the login page. By default, Django looks for it at registration/login.html.

html
<!-- templates/registration/login.html -->
<h2>Login</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Log In</button>
</form>

Handling Registration

Django does not provide a pre-built URL for registration (because every app collects different data on signup), but it does provide the form: UserCreationForm.

python
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            # Log the user in immediately after registering
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    
    return render(request, 'registration/register.html', {'form': form})

Industry Standard: Always log the user in automatically after a successful registration. Forcing them to navigate back to the login page and re-type their newly created credentials is universally hated by users.


2. Restricting Access: @login_required and LoginRequiredMixin

The Problem: You have a login page, but users can still just type /dashboard/ into their browser's address bar and bypass the login page entirely. The server does not know that this specific view should be hidden.

The Solution: We must explicitly tell Django which views require an authenticated user.

For Function-Based Views (FBVs)

We use a decorator. A decorator is a function that wraps another function to modify its behavior. login_required checks if the user is authenticated. If they are, it runs the view. If they are not, it redirects them to the login page.

python
# views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def dashboard_view(request):
    # If the code reaches here, request.user is guaranteed to be authenticated
    return render(request, 'dashboard.html', {'user': request.user})

For Class-Based Views (CBVs)

You cannot use decorators directly on classes in the same way. Instead, Django provides a Mixin. A Mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes.

python
# views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView

class DashboardView(LoginRequiredMixin, TemplateView):
    template_name = 'dashboard.html'

Note: The mixin must be the first argument in the inheritance list.

Imagine a nightclub. The view is the VIP lounge. @login_required and LoginRequiredMixin act as the bouncer checking wrists for stamps. If you do not have a stamp, you are politely (or unpolitely) redirected to the entrance (login page).

By default, the "bouncer" redirects unauthorized users to /accounts/login/. You can change this globally in your settings.py:

python
# settings.py
LOGIN_URL = '/custom-login/'
LOGIN_REDIRECT_URL = '/dashboard/' # Where to go after a successful login
LOGOUT_REDIRECT_URL = '/'          # Where to go after a successful logout

3. Managing Passwords and Handling Session Expiration

The Problem: Users forget their passwords. It happens constantly. Furthermore, if a user logs in on a public computer and forgets to log out, their session remains active, creating a massive vulnerability.

The Solution: Utilize Django's built-in password management views and configure session expiration times in settings.py.

Passwords

Because we included django.contrib.auth.urls earlier, Django already has routes for password resets. You just need to provide the templates:

  • registration/password_reset_form.html (The email input page)
  • registration/password_reset_done.html (The "Check your email" page)
  • registration/password_reset_confirm.html (The new password input page)
  • registration/password_reset_complete.html (The success page)

Fun Fact: In a development environment, Django won't actually send the reset email unless you configure an SMTP server. To see the emails locally, dump them into your terminal by adding this to settings.py:

python
# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Session Expiration

Under the hood, when a user logs in, Django creates a "Session ID" and stores it in the database and in a cookie on the user's browser. Every time the user makes a request, Django reads the cookie, finds the matching session in the database, and identifies the user.

By default, Django sessions last for 2 weeks. In the industry, especially for banking or healthcare apps, this is way too long.

Control this in settings.py:

python
# settings.py

# Expire the session when the user closes their browser
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

# OR set a strict timeout in seconds (e.g., 3600 seconds = 1 hour)
SESSION_COOKIE_AGE = 3600 

4. Extending the User Model: Adding Custom Profile Fields

The Problem: The default Django User model only has a few fields: username, password, email, first_name, and last_name. What if your app needs a phone_number, a bio, or an avatar?

The Solution: We create a Custom User Model.

Industry Standard Warning: You should always set up a Custom User Model at the very beginning of a new Django project, before you run your first python manage.py migrate. Changing the user model mid-project after tables are created makes Django's database routing aggressively complain and requires complex manual database surgeries.

We extend AbstractUser, which keeps all the default authentication logic (hashing, permissions) but allows us to add our own fields.

Step 1: Create the Model

Create an app (e.g., users) and define your model.

python
# users/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # Inherits username, email, password, etc. automatically
    bio = models.TextField(blank=True, null=True)
    phone_number = models.CharField(max_length=15, blank=True)
    
    def __str__(self):
        return self.username

Step 2: Tell Django to use it

In your settings.py, you must explicitly point Django to this new model.

python
# settings.py
AUTH_USER_MODEL = 'users.CustomUser'

What if I forgot and already migrated my database?

If your app is already deep in production and you need to add user fields, do not try to hack AbstractUser into the database. Instead, use the One-To-One Link method. Create a Profile model that attaches to the default user like a sidecar to a motorcycle.

python
# models.py
from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(blank=True)
    
    def __str__(self):
        return f"{self.user.username}'s Profile"

While the OneToOneField approach is safe for existing databases, it requires a secondary database query to fetch the profile data (user.profile.bio), which is slightly slower than AbstractUser (user.bio). Choose AbstractUser when starting fresh!


πŸ“š References and Extra Reading

Challenge

You are building a new social networking application and need to set up a robust user authentication and profile system from the start. Your task is to implement a custom user model, a user registration view, a protected profile page, and configure the necessary URL routing and settings.

Requirements:

  1. accounts/models.py: Define a custom user model named CustomUser that inherits from django.contrib.auth.models.AbstractUser. Add two new fields:

    • bio: A TextField that can be blank.
    • location: A CharField with a max length of 100, which can also be blank.
  2. settings.py: Configure your Django project to use the CustomUser model as the default authentication user model. Also, set the following redirect URLs:

    • LOGIN_REDIRECT_URL should direct users to a URL named profile.
    • LOGOUT_REDIRECT_URL should direct users to the homepage (/).
  3. accounts/forms.py: Create a CustomUserCreationForm that inherits from django.contrib.auth.forms.UserCreationForm. This form should be linked to your CustomUser model and should manage the username, email, bio, and location fields.

  4. accounts/views.py: Implement two Class-Based Views:

    • SignUpView: A generic CreateView that uses your CustomUserCreationForm. Upon successful registration, it should redirect the user to the login URL.
    • ProfileView: A generic TemplateView (you don't need to implement the template itself). This view must be protected, ensuring that only authenticated users can access it. Use the appropriate mixin for this purpose.
  5. URL Configuration:

    • In your main myproject/urls.py, include the default Django authentication URLs (django.contrib.auth.urls) under the path accounts/. Also, include the URLs from your accounts app, also under the accounts/ path.
    • In accounts/urls.py, define the URL patterns for your SignUpView (at signup/, named signup) and ProfileView (at profile/, named profile).

Expected result

Your final code should correctly implement a custom user model, form, views, and configure all related settings and URL patterns across multiple files.

settings.py

python
AUTH_USER_MODEL = 'accounts.CustomUser'
LOGIN_REDIRECT_URL = 'profile'
LOGOUT_REDIRECT_URL = '/'

accounts/models.py

python
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    bio = models.TextField(blank=True)
    location = models.CharField(max_length=100, blank=True)

accounts/forms.py

python
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'email', 'bio', 'location')

accounts/views.py

python
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import CustomUserCreationForm

class SignUpView(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

class ProfileView(LoginRequiredMixin, TemplateView):
    template_name = 'profile.html'

myproject/urls.py

python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
]

accounts/urls.py

python
from django.urls import path
from .views import SignUpView, ProfileView

urlpatterns = [
    path('signup/', SignUpView.as_view(), name='signup'),
    path('profile/', ProfileView.as_view(), name='profile'),
]
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.