Authentication Explained: Essential Information for Beginners

Let's understand with the example of car parking scenario. When you enter your car in to the car parking area then security guard will give you a token on which your car no. will be written and when you came bake security guard will check the token and then match your car's no. then allow you to go. In other word he is basically authenticating the identity of person for taking there right car from the parking lot, If you have no any ticket then guard will not allow you and if yo have token with the no. 3ABP89 then you can only go out with the car have the no. 3ABP89.
In development term if we implement authentication in our system then we don't allow any person who have no any token and we only return or show the data to the person which belongs to that token.
Types Of Authentication
Stateful Authentication
Stateless Authentication
Stateful Authentication
When user login or register then we basically create an ID(session id) from backend and store it into the cookie and also store it in to our database along with user id e.g.
session_id | usere_id |
189765 | 5 |
287478 | 4 |
next time when user request any authenticated site then cookie will also be send with the request , then on the server we get the session_id from the cookie and the find the user associated with that session_id and according to that we will return the data from server, If session_id is not available in our database it means user not registered |
It is called stateful because it maintain the record in to the database.
Problem
Scalability issue: each session we have to store on to the server, If user reaches million then it increase the memory load
if anyone stole your session id then they can easy get the access
server have to maintain the state
Stateless Authentication ([[JWT - JSON Web Token]])
When user login or register the we create an jwt token which itself contain information related user like userid, role, email or etc.
after creating the token we send it to the cookie , We do not store it in our database like we do with session_id
next time when the user will request to our authenticated rout then we get the jwt token from the cookie then verify the cookie using secret , After verifying we get the userid, role or etc. from that token itself then find the user associated with that userid and according to that we will return the data from server, If token is invalid it means user not login/register.
Advantages
Stateless: no need to manage the record in to the database.
Scalable: each request is self contained with the data
expiry, refresh token: we can expire the token according to our need and refresh token will help to create new token after token get expired.
Subscribe to my newsletter
Read articles from shivam kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
