Session Based Authentication
Introduction to User Authentication
Lets us discuss what is user authentication ?
User authentication is a security process where we verify who is trying to access any services of the system.
Lets take an example:
If you want to use facebook, then first of all, you will provide email and password to the facebook server. Once the email and password is verifed, then the facebook redirects you to the homepage. So here, the process of verifying the user who is trying to access the system and its services is called user authentication.
Different Ways to Handle User Authentication
-
There are various ways you can follow to handle user authentication in Django like Session Based Authentication, Token Based Authentication.
-
Here we are going to learn how to implement session based authentication in Django.
HTTP is Stateless Protocol
Before jumping into session based authentication, we need to understand one statement and that is "HTTP is Stateless Protocol".
This means that every HTTP request sent to the server, is independent and it does not relate to any requests that were made earier.
For example: If you send 5 different HTTP requests to the server, the server will have no any idea of how these 5 different HTTP requests are related to each other. The server will treat all these requests as an independent request.
Session Based Authentication
Now, lets discuss about Session based Authentication.
Django supports session based authentication by default. So, we don't need to add any additional package to implement session based authentication.
Now, lets try to visualize the entire process of how session based authentication works in Django.
-
First of all, the user enters username or email and password in the login form.
-
On clicking the submit button, the client sends an HTTP request to the server.
-
When the request reaches to the server, the server validates the given credential and if the credentials are correct, then django creates a new record in the django_session table.
-
In that record, django stores session_key, session_data and expiry date of that session record.
-
After that, the django returns an HTTP response with sessionid in SET_COOKIE header.
Cookies are small blocks of data that are created by the server and stored on the client side or the browser.
SET_COOKIE response header are used by the server to send the cookie data back to the browser.
-
Once the browser gets the HTTP response along with session id in SET_COOKIE header, the browser stores that session id as the cookie.
-
Now, whenever the client sends an HTTP request along with the session id, the server validates that session id against the data stored in the django_session table.
-
If the session id is valid, the requested action is performed by the server.
So, this is the basic overview of how session based authentication works in django.