DEV Community

Prakhar Rai
Prakhar Rai

Posted on

The magic of JWT tokens ✨

Image description

How does a web app know you are authorized to use a resource or not after authentication?

That's where JWT tokens come into play ⚡️

Traditionally what used to happen?

When a client makes an authentication request (username/pass) to the server, the server stores the user info in the memory, generates an id which points to that location and sends that id as a session id (usually in browser cookies).

After that every time you request another resource, the browser verifies the session id and then sends a response.

Problems:

  1. Traditional session IDs require server-side storage to maintain session state. This can be resource-intensive and challenging to scale in distributed systems.

  2. CORS restrictions can make it difficult to share session IDs securely across different domains or APIs.

  3. Since the information mapping to session id is stored in server, managing session state across multiple servers or instances can be complex.

How does JWT solve these problems? ⚡

Structure of a JWT token: [𝘏𝘌𝘈𝘋𝘌𝘙].[𝘗𝘈𝘠𝘓𝘖𝘈𝘋].[𝘚𝘐𝘎𝘕𝘈𝘛𝘜𝘙𝘌]

  1. JWT tokens are stateless and contain all necessary information, like user roles and permissions, in the token itself. Servers can verify tokens without needing to store session information.

  2. Since they contain all the info, they don't need to be stored on the server!

  3. JWT tokens can be used as a standardized authentication mechanism, allowing users to access multiple services or APIs with a single token.

  4. The signature is used to determine if the token was changed on the client's end.

  • How is the signature made: Algorithm: 𝘏𝘔𝘈𝘊𝘚𝘏𝘈256(𝘣𝘢𝘴𝘦64𝘜𝘳𝘭𝘌𝘯𝘤𝘰𝘥𝘦(𝘩𝘦𝘢𝘥𝘦𝘳𝘴) + "." + 𝘣𝘢𝘴𝘦64𝘜𝘳𝘭𝘌𝘯𝘤𝘰𝘥𝘦(𝘱𝘢𝘺𝘭𝘰𝘢𝘥), [𝘺𝘰𝘶𝘳𝘴𝘦𝘤𝘳𝘦𝘵𝘬𝘦𝘺]).

This is how the server validates the token, it decodes the header and payload and it uses the algo above to create the new_signature and then verifies the new_signature with the signature in the JWT token.

~ @prakharrai1609

Top comments (0)