Django require authentication on all pages
This recipe is an old one but a good one. In some Django projects you will want to force a user to login for all or almost all pages. Stop copy pasting that login_required decorator on all your views! Using this middleware you very easily can force authentication on all pages you want.
To accomplish this we will create a new Django Middleware class called LoginRequiredMiddleware. Simply copy-paste the code below in a middleware.py file in one of your Django applications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
from django.http import HttpResponseRedirect from django.conf import settings from re import compile EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: """ Middleware that requires a user to be authenticated to view any page other than LOGIN_URL. Exemptions to this requirement can optionally be specified in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which you can copy from your urls.py). Requires authentication middleware and template context processors to be loaded. You'll get an error if they aren't. """ def process_request(self, request): assert hasattr(request, 'user'), "The Login Required middleware\ requires authentication middleware to be installed. Edit your\ MIDDLEWARE_CLASSES setting to insert\ 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\ work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\ 'django.core.context_processors.auth'." if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(settings.LOGIN_URL) |
Installing the middleware
To install the middleware you simply add it to the list of middleware in your project’s settings file. We will talk about Django’s Middleware in a later article but for now just now that this kind of middleware sits perfectly at the bottom of the default middleware list:
1 2 3 4 5 6 7 8 9 10 11 12 |
MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'myapplication.middleware.LoginRequiredMiddleware', ] |
Configure any URLs to exclude
By default this middleware will redirect all requests from unauthenticated users to the LOGIN_URL. If you want to exclude any URLs from this (such as an about page or registration page) you can specify a setting called LOGIN_EXEMPT_URLS:
1 2 3 4 5 |
LOGIN_EXEMPT_URLS = ( r'^$', r'^about$', r'^register$', ) |
In the example above we exclude the ‘homepage’ of our application at /, the about page at /about and the registration page at /register. There is no need to specify the url of your login page as this is done automatically by the middleware.
And that’s it! All requests that come from an unauthenticated user to an URL that’s not in your LOGIN_EXEMPT_URLS setting will be redirected to your login view.
4 Replies to “Django require authentication on all pages”
It looks like this recipe doesn’t work with Django 1.10 due to an update in the way middleware works 🙁
Thanks for posting this. Very helpful for a Django newbie like me.
Small modification for Django 1.10. Import the MiddlewareMixin from django.utils.deprecation. Modify the class to inherit from the MiddlewareMixin.
If your LOGIN_URL happens to be the root page, you will have to change EXEMPT_URLS to an empty list.
This works for Django 1.10
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip(‘/’))]
if hasattr(settings, ‘LOGIN_EXEMPT_URLS’):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
def LoginRequiredMiddleware(get_response):
“””
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally be specified
in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
you can copy from your urls.py).
Requires authentication middleware and template context processors to be
loaded. You’ll get an error if they aren’t.
“””
# One-time configuration and initialization.
def middleware(request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = get_response(request)
if not request.user.is_authenticated():
path = request.path_info.lstrip(‘/’)
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(settings.LOGIN_URL)
# Code to be executed for each request/response after
# the view is called.
return response
return middleware
I have noticed you don’t monetize your website, don’t waste your traffic, you can earn additional
bucks every month because you’ve got high quality content.
If you want to know how to make extra $$$, search for:
Mertiso’s tips best adsense alternative