DEV Community

Cover image for Understanding JSON Web Tokens (JWT) for Secure Information Sharing
Vishal Yadav
Vishal Yadav

Posted on

Understanding JSON Web Tokens (JWT) for Secure Information Sharing

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:

  1. Security: JWTs are digitally signed, ensuring that the data is not tampered with.
  2. Scalability: Being stateless, JWTs do not require server-side storage, making them ideal for distributed systems.
  3. Compact: JWTs are compact and can be easily sent via URL, POST parameter, or HTTP header.
  4. 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.

Jwt

Structure of a JWT

A JWT consists of three parts: Header, Payload, and Signature. These parts are separated by dots (.)

Header.Payload.Signature
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The signature is then Base64Url encoded and forms the third part of the JWT.

Do

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.

Decode
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

JWT in Real-World Scenarios

Let's explore some practical applications of JWTs in 2024:

  1. 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.

  2. 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.

  3. 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.

  4. 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

  1. Keep It Secret, Keep It Safe:
    Protect your signing keys like they're the One Ring. Use key management services and rotate keys regularly.

  2. Don't Overpack Your Tokens:
    Keep payloads small. JWTs are not a replacement for databases!

  3. Set Reasonable Expiration Times:
    Short-lived tokens (think minutes, not days) minimize the risk if a token is compromised.

  4. Implement Token Revocation:
    Use a token blacklist or a Redis cache to invalidate tokens when needed.

  5. 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.

Top comments (10)

Collapse
 
charlesr1971 profile image
Charles Robertson • Edited

I tend to just add a user id to the payload.
Then you can get the rest of the data from the DB.
It is also possible to use a JWE, which is an encrypted web token. This adds an extra level of security.

Collapse
 
franciscocorrales profile image
Francisco Corrales Morales

I've also added the user's email to the JWT in an app that getting that from the Database would be slow. And the email was a recurring read property. So it saved us time by keeping it in the payload.

Collapse
 
shimanta_microcodes profile image
Shimanta Das

Awesome 👍👍👍

Collapse
 
vyan profile image
Vishal Yadav

Tq!

Collapse
 
ari_gaskins_aaf74acedca52 profile image
Ari Gaskins

You explained this very well. Thank you for sharing!

Collapse
 
kimss profile image
kelvin isaac phiri

Useful

Collapse
 
sirzarganwar profile image
Martin Jirasek

Simple and informative. Thx!

Collapse
 
francois_7c96a8d profile image
Francois de Jager

Good

Collapse
 
t_pavithiravalavan_a3eb75 profile image
T Pavithiravalavan

Great Explanation 😊

Collapse
 
hazemdev profile image
Hazem shabaan elkady

ممتاز exccellent👌