Get Started with JSON Web Tokens for Your Next Project

The Basics of JWT

CHAIRI Chaimae
5 min readFeb 27, 2024
JSON Web Token icon by itorizon.com

JSON Web Tokens (JWT) are like secret notes passed between computers on the internet. These notes are made up of three parts:

🔶 The header that says what type of note it is.

{
"alg": "RS256",
"typ": "JWT"
}
  • alg: The algorithm used for signing the token. In this example, "RS256" represents RSA with SHA-256.
  • typ: The type of the token, which is JWT.

After encoding in Base64, the header looks like: eyJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9

🔶 The payload with the actual information.

{
"sub": "987654321",
"role": "admin",
"exp": 1679818932
}

After encoding in Base64, the payload looks like: eyJzdWIiOiAiOTg3NjU0MzIxIiwgInJvbGUiOiAiYWRtaW4iLCAiZXhwIjogMTY3OTgxODkzMn0

🔶 The signature that ensures the note hasn’t been tampered with.

In this example, let’s say we’re using an asymmetric algorithm like RSA. The signature is created using the private key.

signature = RSASignature(base64UrlEncode(header) + "." + base64UrlEncode(payload), privateKey)

Let’s put on our coding capes! the resulting JWT is a combination of the Base64-encoded header, payload, and the signature. The signature is used for verification, ensuring the authenticity and integrity of the JWT. And here’s the final JWT:

eyJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiOiAiOTg3NjU0MzIxIiwgInJvbGUiOiAiYWRtaW4iLCAiZXhwIjogMTY3OTgxODkzMn0.SOME_OTHER_ENCODED_SIGNATURE

=> Imagine it as a digital secret code that helps computers trust each other.

Use Cases

JWTs serve as a versatile and secure way to transmit data between parties.

API Authentication:

Stateless Sessions:

Authorization:

Information Exchange:

JWT Authentification @atatus.com

How JWTs Enhance Security?

Think of JWTs have a special signature that acts like a lock. This lock ensures that the information inside the JWT hasn’t been changed by anyone. So, when computers send JWTs to each other, they can be sure that the messages haven’t been messed with during their journey.

Common Challenges and Best Practices:

When working with JWTs, sometimes there are tricks that hackers try. But don’t worry! There are best practices to keep the bad guys away. It’s like having a shield that protects our digital adventures. By following these tips, we make sure our online world stays safe and sound.

Security Risks:

⚠️ JWTs must be handled with care. Although they provide a secure way to transmit data between parties, improper implementation can lead to vulnerabilities.

✔️ Always validate the token’s signature to ensure its authenticity and integrity.

Size and Efficiency:

⚠️ While JWTs are designed to be compact, they can still become relatively large when they contain multiple claims (information).

✔️ Be mindful of the token’s size, especially when transmitting it over the network.

No Invalidation Mechanism:

⚠️ JWTs are stateless, This means that there’s no built-in mechanism to invalidate a token before it expires.

✔️ If you need to revoke access for a specific user, it becomes challenging to do so before the token’s expiration.

Storage on the Client:

⚠️ Storing JWTs securely on the client side can be tricky.

✔️ Avoid storing sensitive information (such as passwords or credit card numbers) directly in the token payload.

Best Practices for Working with JWTs:

👍 Use Strong Encryption

  • Choose a robust cryptographic signing algorithm like RS256 to sign JWTs.
  • Avoid using insecure algorithms or plaintext.

👍 Keep Sensitive Data on the Server:

  • Refrain from including sensitive information in the token payload.
  • Store critical data (like user credentials) securely on the server.

👍Implement Token Refresh Mechanism:

  • Use refresh tokens alongside JWTs to handle token expiration.
  • Refresh tokens allow users to obtain a new access token without re-authenticating.

👍 Securely Store JWTs:

  • If storing JWTs in cookies, set the HttpOnly flag to prevent client-side JavaScript access.
  • Consider using SameSite attributes to control cookie behavior.

👍 Use HTTPS:

  • Always use HTTPS when transmitting JWTs to ensure data confidentiality during transit.
  • HTTPS provides an additional layer of protection beyond JWTs.

JWT vs Alternatives:

1️⃣ JWT (JSON Web Tokens):

Superpower: Speedy and versatile.

Use Case: When you need a lightweight, self-contained token for authentication, authorization, and data exchange.

Strengths:

  • Compact format (easy to transmit).
  • Stateless (no server-side storage needed).
  • Customizable claims.

Weaknesses:

  • No built-in token revocation (requires additional mechanisms).
  • Payload size can grow if too many claims are added.

2️⃣ OAuth 2.0 Tokens (Access Tokens):

authlete.com

Superpower: Social connector.

Use Case: When integrating with third-party services like social logins and APIs.

Strengths:

  • Standardized (widely adopted).
  • Supports different grant types (authorization code, client credentials, etc.).
  • Scalable for large ecosystems.

Weaknesses:

  • Complexity (requires understanding OAuth flows).
  • Token introspection needed for validation.

3️⃣ Session Cookies:

Superpower: Old-school charm.

Use Case: Traditional web applications.

Strengths:

  • Widely supported by browsers.
  • Automatic handling (cookies sent with every request).
  • Server-side session management.

Weaknesses:

  • Stateful (requires server storage).
  • Vulnerable to CSRF attacks.
  • Not suitable for APIs.

4️⃣ API Keys:

Superpower: Simplicity.

Use Case: When securing APIs or limiting access.

Strengths:

  • Easy to implement.
  • Stateless (no server storage).
  • Suitable for rate limiting.

Weaknesses:

  • Lack of granularity (all-or-nothing access).
  • Hard to revoke (requires manual intervention).

5️⃣ SAML (Security Assertion Markup Language):

networkencyclopedia.com

Superpower: Enterprise trust.

Use Case: Single Sign-On (SSO) for large organizations.

Strengths:

  • Federated identity (cross-domain trust).
  • Robust security features.
  • Extensible.

Weaknesses:

  • Complex setup.
  • Heavyweight (XML-based).

In summary, JWTs are versatile tokens facilitating secure data exchange. Their compact format ensures efficiency in transmission. With cryptographic signatures, JWTs provide a trustworthy authentication mechanism. Embracing JWTs enhances data integrity and security in modern web development.

So, discover the secrets of JWTs effortlessly! Begin your easy journey to understanding now!

--

--

CHAIRI Chaimae
CHAIRI Chaimae

Written by CHAIRI Chaimae

This space's to document my learning and track my progress. Hope it helps someone somewhere. You're welcomed!

Responses (1)