Demystifying JSON Web Tokens (JWTs): A Comprehensive Guide
Navigating the World of JWTs
In the world of web development and security, JSON Web Tokens (JWT) have become an essential tool for Authentication and Authorization. JWTs provide a secure and compact way to transmit information between client and server. In this guide, we will explore what JWT is, how they work, and why we need JWTs in the first place. So, let's delve into the guide.
Authentication and Authorization
Authentication is the process of verifying the identity of a user, device, or system. It typically involves the presentation of credentials, such as a username and password, to prove one's identity.
Authorization is the process of granting or denying access to specific resources or actions based on the user's privileges, roles, or permissions. It ensures that authenticated users can only access resources or perform actions they are explicitly permitted to access.
To perform Authentication, there are certainly two most popular ways on the web.
1.Using Cookies (Stateful)
The traditional approach is Cookie-based server-side sessions. In the traditional approach, applications use sessions and cookies to store the user and perform authentication and authorization.
The process begins with a user filling out their username and password and submitting to a server. As soon as the request reaches the server, the server is going to perform the authentication to make sure that the user is correct. If authentication is successful, the server is going to store the ID of the user inside the session, which is stored inside the server memory. This unique ID maps to the part of the memory, where the user info is stored. This unique ID is sent back to the client (browser), which is then stored inside a cookie. So now the browser always has the session ID in the form of a cookie and every time the client makes a request, it sends this cookie along with the request to the server. The server then checks in the server memory whether there is any ID that corresponds to the id that it received from the user. If so (authorized), the server responds back to the client.
2.Using JWT's (Stateless)
The other approach to perform authentication is using JWTs. JWT instead of actually using these cookies, uses JSON Web Token, which is what JWT stands for, to do the authorization/authentication.
It works very similarly in the beginning, where the user makes a post request to the server with login credentials. But instead of storing the user info inside the session memory, what happens is server creates json web token (JWT). Here the server actually encodes and serialises the sign with its own secret key, So the server knows if you tamper it. Then it sends back the JWT to the client.
Notice the main difference here, nothing is stored on the server, and that's why this type of authentication is stateless. The JWT that the client received will have all the information in it. This JWT is then stored in a local storage on the client side. And everytime the client makes the request to the server, this JWT is sent along with request. The server verifies the JWT signature and sents back the response to the client.
How JWT works
A JWT consists of three parts:
Header: The header typically consists of two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.
Payload: The payload contains claims, which are statements about an entity (typically, the user) and additional data. There are three types of claims:
Registered Claims: These are predefined claims with well-known meanings, such as "iss" (issuer), "exp" (expiration time), "sub" (subject), and others.
Public Claims: These are custom claims defined by the JWT standard but are not mandatory. They can convey non-sensitive information.
Private Claims: These are custom claims created by the parties involved in the token exchange. Examples are "role" of a user (admin/user).
Signature: To create the signature part, you take the encoded header, the encoded payload, a secret, and the algorithm specified in the header and sign that. It is used to verify that the user has not tampered the token.
The three parts of a JWT, when combined, form a string in the following format: {header}.{payload}.{signature}
. The three parts of JWT are separated by periods. The recipient of the token can decode the header and payload, then base64 encodes the decoded part and hash it with a particular algorithm and verifies whether the signature part of the JWT part is the same as the present hashed value. When you won't get the same value then it indicates that JWT is tampered.
Why you should use JWTs
Let's say for suppose there is a company that has two servers, the company is very large that they need two different servers to handle all of its users coming to the server and they have a load balancer to distribute the traffic to different servers.
Now let's say a client is accessing server A for a while, and for some reason, that server got really busy and shifts the client to server B. But the user session is not stored on server B, it's only on server A and so the user has to login back.
The solution to this is to introduce a single Cache Service for all the instances. This is a typical use case of the Redis Cache Service. The drawback to this solution is that, there will be now a single point of failure for the application.
But with JWT the user is stored at client side, so no matter how many different servers you have and no matter how many different application load balancers or anything that you have, you can always authenticate with any of those servers as long as all the servers have the same secret key. This JWT is really useful when your application has microservices.
Use cases of JWTs over Cookies
Statelessness:
Web applications can be built to be stateless, meaning they don't store user data on the server. JWTs contain all necessary information, allowing the server to verify and trust incoming requests without the need for server-side sessions.
Scalability:
JWTs are designed for distributed systems and microservices architecture. They facilitate secure communication between different components without the need for constant centralized authentication.
Single Sign-On (SSO):
JWTs are a crucial component of Single Sign-On systems, allowing users to log in once and access multiple applications seamlessly without re-entering credentials.
Cross-Origin Resource Sharing (CORS):
JWTs enable secure cross-origin requests. They can be included in HTTP headers, allowing web applications hosted on different domains to interact securely. Whereas cookies are subject browser's same-origin policy, which makes cross-origin request more challenging.
[ In case if you don't know what cross-origin requests are, A cross-origin request occurs when a web page from one domain attempts to make a request (e.g., HTTP request) to a different domain. This is often the case when a web page hosted on one domain wants to fetch resources (e.g., data, images, or scripts) from another domain or make requests to APIs hosted on different domains. ]