Token Based Authentication (JWT)

After discussing the session based authentication, let’s explore the JWT(JSON WEB TOKENS).

Here the authentication flow is like when user actually try to log in so SERVER match that client information with the USER DATABASE and if the parameters (email, password) are matched successfully, so the SERVER assigns a token to the USER. The token is actually passed to the client and with each subsequent request the SERVER VERIFIES THE USER VIA THE SECRET SIGNATURE ON THAT TOKEN, SIGNATURE WHICH IS ACTUALLY MADE BY THE SERVER ITSELF IS VERIFIED VIA THE SERVER’S OWN SECRET KEY, AS SECRET_KEY IS USED TO MAKE THE SIGNATURE. You can think of SECRET_KEY as an authorized STAMP. With that the best part is there is no need to store that TOKEN in server memory(stateless authentication) as token contains all necessary user information.

The token actually looks something like this: HEADER.PAYLOAD.SIGNATURE

Header: Initial part of the token, so the system knows it’s a JSON Web Token. It also specifies the algorithm used to create the signature (e.g., HS256 for HMAC-SHA256 or RS256 for RSA).

Payload: Contains necessary non-sensitive USER information.

Signature: Used for verifying that token is created by the SERVER itself. The server does not store the JWT. Instead, it uses the SECRET_KEY to verify the signature of the incoming token. SECRET_KEY is what SERVER owns.

TOKENS are stored on the CLIENT SIDE, either in COOKIES[HTTP ONLY FOR SECURITY], LOCAL STORAGE OR SESSION STORAGE(on browser).

Advantage is that SERVER storage is saved, using TOKENS is scalable and in modern SERVERLESS architecture it is applicable!