0
0
Djangoframework~5 mins

Authentication middleware in Django

Choose your learning style9 modes available
Introduction

Authentication middleware helps check who a user is before they use parts of a website. It keeps the site safe by making sure only allowed users can see certain pages.

When you want to make sure only logged-in users can visit some pages.
When you need to check user identity before showing personal information.
When you want to redirect users to login if they are not signed in.
When you want to add user info to requests so views can use it easily.
Syntax
Django
MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # other middleware
]
This middleware is usually added in the settings.py file inside the MIDDLEWARE list.
It works together with Django's authentication system to attach user info to each request.
Examples
This example shows AuthenticationMiddleware placed after session middleware, which is required for it to work properly.
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.common.CommonMiddleware',
]
Inside a view, you can check if the user is logged in using request.user.is_authenticated thanks to the middleware.
Django
from django.http import HttpResponse

def my_view(request):
    if request.user.is_authenticated:
        return HttpResponse('Hello, ' + request.user.username)
    else:
        return HttpResponse('Please log in.')
Sample Program

This example shows how AuthenticationMiddleware works with the @login_required decorator to protect a view. If a user is not logged in, they will be redirected to the login page automatically.

Django
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

@login_required
def secret_page(request):
    return HttpResponse(f"Welcome, {request.user.username}! This is a secret page.")

# settings.py snippet
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.common.CommonMiddleware',
]

# This setup ensures only logged-in users can access secret_page view.
OutputSuccess
Important Notes

AuthenticationMiddleware depends on SessionMiddleware, so order matters.

It adds a user attribute to every request, which you can use in views and templates.

Use decorators like @login_required to easily protect views.

Summary

Authentication middleware checks who the user is on every request.

It must be added to the MIDDLEWARE list in settings.py after session middleware.

It makes user info available as request.user for your views.