In the world of software architecture, especially when dealing with multiple parties and secure authentication/authorization, a robust mechanism for sharing proof of identity is crucial. One of the most secure and widely used methods is the JSON Web Token (JWT) 🔏.
In this blog, we'll dive deep into what JWTs are, how they work, and why they are an excellent choice for secure data transmission.
What is a JSON Web Token (JWT)?
A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Why Use JWT?
JWTs are stateless, meaning the server does not need to store token information in the session. This stateless nature makes JWTs scalable and suitable for client-server applications and distributed systems. Here are some key reasons why JWTs are preferred:
- Security: JWTs are digitally signed, ensuring that the data is not tampered with.
- Scalability: Being stateless, JWTs do not require server-side storage, making them ideal for distributed systems.
- Compact: JWTs are compact and can be easily sent via URL, POST parameter, or HTTP header.
- Self-contained: The payload of a JWT contains all the information necessary for the intended user, eliminating the need to query the database multiple times.
Structure of a JWT
A JWT consists of three parts: Header, Payload, and Signature. These parts are separated by dots (.)
Header.Payload.Signature
Let's break down each component:
1️⃣ Header
The header typically consists of two parts: the token type, which is JWT, and the signing algorithm being used, such as HMAC, SHA256, or RSA.
Example:
{
"alg": "HS256",
"typ": "JWT"
}
This JSON object is then Base64Url encoded to form the first part of the JWT.
2️⃣ Payload
The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
-
Registered claims: These are a set of predefined claims which are not mandatory but recommended, such as
iss
(issuer),exp
(expiration time),sub
(subject),aud
(audience), and others. - Public claims: These can be defined at will but should be collision-resistant or be namespaced.
- Private claims: These are custom claims created to share information between parties that agree on using them.
Example:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
This JSON object is also Base64Url encoded to form the second part of the JWT.
3️⃣ Signature
To create the signature part, you have to take the encoded header, the encoded payload, a secret, and the algorithm specified in the header. The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.
For example, if you want to use the HMAC SHA256 algorithm, the signature will be created like this:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
The signature is then Base64Url encoded and forms the third part of the JWT.
How JWT Works
When a client wants to access a protected resource, it includes the JWT in the Authorization header of the HTTP request, similar to a Bearer Token. The server performs a set of steps to validate the JWT. If all the validation steps pass, the server considers the JWT valid and grants access to the requested resource.
Here are the steps:
1️⃣ Decoding the JWT: The server decodes the JWT to extract the header and payload.
2️⃣ Verifying the Signature: The server verifies the signature by reapplying the signing algorithm to the header, payload, and secret key. If the recalculated signature matches the signature in the JWT, it indicates that the token has not been tampered with.
3️⃣ Checking Expiration: The server checks the expiration time in the payload to ensure the token is not expired.
4️⃣ Additional Checks: Depending on the application's requirements, the server may perform additional checks, such as verifying the token issuer or checking the token against a list of revoked tokens.
JWT in Real-World Scenarios
Let's explore some practical applications of JWTs in 2024:
Single Sign-On (SSO) Wonderland:
Imagine logging into your company's ecosystem once and accessing multiple services seamlessly. JWTs make this dream a reality, securely passing your authentication state across different domains.Microservices Choreography:
In the world of microservices, JWTs act as the perfect messenger. They carry authentication and authorization info between services, ensuring secure and efficient communication.IoT Device Authentication:
As your smart fridge talks to your smart toaster (yes, we're there in 2024), JWTs ensure that only authorized devices can exchange data.Serverless Function Authorization:
With the rise of serverless architectures, JWTs provide a stateless way to authorize function invocations without the need for persistent sessions.
JWT Best Practices for 2024
Keep It Secret, Keep It Safe:
Protect your signing keys like they're the One Ring. Use key management services and rotate keys regularly.Don't Overpack Your Tokens:
Keep payloads small. JWTs are not a replacement for databases!Set Reasonable Expiration Times:
Short-lived tokens (think minutes, not days) minimize the risk if a token is compromised.Implement Token Revocation:
Use a token blacklist or a Redis cache to invalidate tokens when needed.HTTPS All the Way:
Always transmit JWTs over encrypted connections. No exceptions!
JWT in Practice
JWTs are incredibly versatile and can be used in various scenarios. For example, they are commonly used to authorize backend APIs while maintaining the same set of permissions. Many modern applications, including Appwrite, support JWT-based authentication to ensure secure and efficient authorization processes.
Conclusion
JSON Web Tokens (JWT) are a powerful tool for secure information sharing in modern web applications. They provide a compact, self-contained, and secure way to transmit data, making them an excellent choice for various use cases, from stateless authentication to securing APIs. By understanding and implementing JWTs, developers can enhance the security and scalability of their applications.