Django — middleware authentication

In this article, we shall see how to authenticate the users in the middleware. In my Django project, I wanted to authenticate the users in the middleware instead of authenticating them in the views functions. If you are using Django Rest Framework the authentication automatically happens in the middleware. But, if we are not using the DRF or want to authenticate manually in the middleware you can make use of this article.

Photo by Jason Blackeye on Unsplash
app structure

The middleware

In Django middleware, there is a method called process_view(). Theprocess_view() method is called just before Django calls the view. You can name the middleware class whatever you want but the method name should be process_view() only.

process_view(request, view_func, view_args, view_kwargs)
  1. view_func: This is the function itself and not the name. The function from the views.py file that our urls.py routes our request to is the view_func.
  2. args and view_kwargs: view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view.
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class ProcessRequestMiddleware(MiddlewareMixin): def process_view(self, request, view_func, *view_args, **view_kwargs):
# do something

How to make it work?

We are going to make use of this HttpResponse object to return a response object, in the middleware itself with a status code of 401 if the user is not authenticated.

Check if the user is authenticated

First, we will retrieve the user object from the request object like this.

user = request.user
user = request.user
if user.is_authenticated:
return HttpResponse(status=200)
else:
return HttpResponse(status=401)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_user_agents.middleware.UserAgentMiddleware',
'student.middleware.ProcessRequestMiddleware'
]

Conclusion

Hope this article is helpful. Happy coding!

Python Developer | Django Developer | Python Enthusiast