Django — middleware authentication

Allwin Raju
3 min readDec 7, 2020

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.

Read the full article here: https://allwin-raju-12.medium.com/django-middleware-authentication-879d5e6391d1?source=friends_link&sk=a4379eb99033c21f54fd53487e2054a7

Photo by Jason Blackeye on Unsplash

In order to add a middleware function, we have to create a function somewhere in our project and add the name of the middleware class to the settings.py file under the MIDDLEWARE list.

I have a student app like this in my Django project.

app structure

I have added a new file called middleware.py. I will be creating a class that will check if the user is authenticated here.

The middleware

In Django middleware, there is a method called process_view(). Theprocess_view() method is called just before Django calls the…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

What are your thoughts?