Introduction :#
JWT stands for JSON Web Token. A JSON Web Token is a digitally signed token used to securely transmit information between parties in a compact format. It’s like a digital passport that allows users to access different parts of a web application without having to repeatedly log in. The token itself contains all the necessary information, and its signature ensures that the data has not been tampered with. This makes JWT a powerful tool for enabling stateless authentication, where the server doesn’t need to remember who you are, but can still trust the information you provide each time you interact with it.
If you want to inspect the structure of a JWT, you can visit jwt.io.
Example:
Let’s imagine, when you buy a movie ticket, it serves as proof that you have paid for a seat. The ticket contains information such as the movie time, seat number, and a unique code (like the data in a JWT). Once you enter the theater, you show your ticket (JWT) to gain access without needing to verify your identity again at each point inside the theater.
Why use JSON Web Token (JWT)#
Using JWTs provides a robust, scalable, and secure solution for authentication and authorization, especially in modern, distributed, and decentralized systems like microservices architectures. Their stateless nature makes them ideal for cross-domain authentication and scaling across multiple servers, while their security features ensure the integrity and trustworthiness of the data they carry.
- Stateless
JWTs are self-contained tokens that hold all the necessary information for authentication within the token itself. Once a JWT is issued, the server doesn’t need to keep track of user sessions or store any session data.
This stateless nature simplifies server architecture, as it eliminates the need for session storage or database lookups for each request, making JWTs ideal for RESTful APIs.
Example:
It’s like carrying a passport with all your travel visas. You don’t need to check in with an embassy each time you enter a country; the passport itself proves you have the right to enter.
- Scalable in Distributed Systems
Since JWTs are stateless, they can easily be used in distributed systems where multiple servers handle incoming requests. There’s no need to share session data between servers because the JWT contains all the required information.
This makes scaling applications horizontally much easier, as any server in the network can validate the JWT and process the request without relying on a central session store.
Example:
Imagine attending a large conference with multiple entry points. Your badge (JWT) allows you to enter through any door without the need to check a central list of attendees.
- Cross-Domain Authentication
JWTs can be used to authenticate users across different domains. Because they are self-contained and signed, a JWT issued by one domain can be trusted by another, enabling seamless cross-domain authentication.
This is particularly useful in scenarios like Single Sign-On (SSO), where a user can log in once and gain access to multiple related applications or services.
Example:
Think of a university student ID that grants access to various facilities across campus, such as the library, gym, and dorms, without needing separate logins for each building.
- Ideal for Decentralized Systems and Microservices
In microservices architectures, where different services need to communicate with each other, JWTs provide a simple and secure way to verify requests. Each service can independently verify the token without needing to rely on a centralized authentication service.
This decentralization enhances the resilience and independence of microservices, as each service can handle authentication locally, improving performance and reliability.
Example:
It’s like having a universal keycard that opens doors in a complex with multiple independent buildings. Each building recognizes and accepts the keycard without needing to check with a central authority.
- Highly Secure
JWTs are signed using a secret key or a public/private key pair, ensuring that the token’s contents cannot be altered without invalidating the signature. This provides a high level of security and trust, as the server can be confident the token hasn’t been tampered with.
JWTs can securely transmit sensitive information, such as user roles or permissions, and can be protected from unauthorized access by using encryption.
Example:
Think of a secure lock on a treasure chest. When the lock (signature) is secure, you can trust that the contents of the chest haven’t been accessed or tampered with. Only someone with the right key can open it, ensuring that the treasures inside (sensitive information) remain safe from unauthorized access.
JWT Dependencies#
Add these dependencies to your pom.xml
in a Maven project to enable JWT handling within your Spring Boot application. With these, you can easily create, sign, and verify JWT tokens in your application.
JWT Creation#
Think of JWT as a digitally signed message. It consists of three parts: a header, payload (which contains the data), and a signature (which ensures that the message hasn’t been tampered with).
- Sample Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9**.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.**SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- JWT Header:
Contains metadata about the token, such as the signing algorithm (HS256
) and token type (JWT
). This is base64url encoded.
- JWT Payload:
Contains the claims (e.g., user information, expiration time). This is also base64url encoded.
- Secret Key:
Used to sign the token, ensuring its integrity.
- Signature Generation:
- The encoded header and payload are concatenated with a period (
.
) in between. - This concatenated string is hashed using the HMAC-SHA256 algorithm, along with the secret key.
- The result is base64url encoded to produce the encoded signature.
- The encoded header and payload are concatenated with a period (
- Final Token:
The token is the concatenation of the encoded header, payload, and signature, separated by periods (.
).