DEV Community

Cover image for JSON WEB TOKENS [ JWT ]
Bek Brace
Bek Brace

Posted on • Updated on

JSON WEB TOKENS [ JWT ]

In my research and preparation for a new video on my YouTube channel, where I am demonstrating how to use JWT ( why JAWT ? why is the A in the middle? ) for authentication in Flask microframework, I decided to write a script for better understanding and to have a clear picture about what is going on underneath the hood.

Here it is ..

There are 2 ways to make user authentication on the web:

Sessions and Tokens

And the traditional approach is cookie based server side sessions.

1- The process begins when the user logs in with username and password and submits to the server.
2- Then the server stores a session in the database and responds by sending a session ID to your client computer, more specifically hands it over to your browser.
3- which stores this session ID in a cookie, and a cookie is a text file saved in your local storage in the browser in a form of
{key: value} pairs.
4- that will be sent back to the server for every subsequent request; and the server will respond to that corresponding request for the current logged in user.

In other words, we have a stateful session between the frontend client and the backend server.

This approach is good, but lacks some security measure, and can be vulnerable to different malicious attacks [ CSRF ]
Where the attacker points the user to a site they logged into to perform actions such as changing password or secret question; however the risk is very low if you're using modern frameworks like Rails and Django to implement your code for your website

The bigger problem is that you need to store your session ID in a database or on the server as most of today's cloud apps are scaled horizontally this can be a huge bottleneck for production.

And here comes the Token-Based Authentication

So, the process begins the same way as with server-side session :

1- user submits login form to the server,
2 -but instead of storing a session in the database and responding with a session ID, the server creates a JWT with a private key.
3 - Then the server sends this JWT Token to be kept in the local storage in your browser
4 - On future requests, the JWT will be added to the authorization header prefixed by the bearer of that token, the server only needs. to validate the signature; and nothing is stored on the server like in the sessions scenario.

The most important thing to understand :

A- In sessions, the authentication state is handled on the server , while JWT tokens are managed on the client.

B- Stateful protocol--> Uses Sessions and store sessions in database while handling the client a session ID.

C- Stateless protocol --> No session information is retained by the server (like HTTP and Internet Protocol).

The End.

Top comments (0)