Authentication Middleware Example

A snippet showing how to add authentication checks via middleware.


# middleware.py

from django.shortcuts import redirect
from django.conf import settings
from django.urls import reverse

class AuthRequiredMiddleware:
    """Enforce authentication globally with simple allowlist exceptions."""
    def __init__(self, get_response):
        self.get_response = get_response
        # Paths that do not require auth (prefix match)
        self.public_paths = getattr(settings, 'PUBLIC_PATHS', [
            reverse('login'),
            reverse('password_reset'),
            '/admin/login/',
            '/static/',
            '/media/',
        ])

    def __call__(self, request):
        path = request.path
        is_public = any(path.startswith(p) for p in self.public_paths)

        if not is_public and not request.user.is_authenticated:
            login_url = reverse('login')
            return redirect(f"{login_url}?next={path}")

        return self.get_response(request)
  

# settings.py

MIDDLEWARE = [
    # ...
    'your_app.middleware.AuthRequiredMiddleware',
    # Keep AuthenticationMiddleware enabled (Django default)
]

# Optional: customize public paths (prefix match)
PUBLIC_PATHS = [
    '/accounts/login/',
    '/accounts/password-reset/',
    '/admin/login/',
    '/api/public/',
    '/static/',
    '/media/',
]
LOGIN_URL = '/accounts/login/'
  

# urls.py (example named route)

from django.urls import path
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('accounts/login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
]
  
Explanation:
  • This middleware redirects unauthenticated users to the login page, preserving the original URL via ?next=.
  • PUBLIC_PATHS defines prefixes that bypass auth checks (e.g., static files, password reset, public APIs).
  • Keep Django's built‑in AuthenticationMiddleware enabled so request.user is available.
  • Prefer named routes via reverse() to avoid hard‑coding paths; fall back to strings if needed.
  • Category Middleware
  • Total Views 1067
  • Last Modified 24 March, 2026
  • Tags #middleware #authentication #auth #login
Previous snippet
Timing Request Duration
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.