Skip to main content

Command Palette

Search for a command to run...

πŸ” Understanding JWT (JSON Web Tokens) β€” The Developer-Friendly Guide

"A beginner-to-pro guide on what JWT is, how it works, and where to use it for secure authentication, authorization, and data transfer."

Updated
β€’4 min read
P

πŸ‘¨β€πŸ’» I'm Praveen Gupta, a Senior Backend Engineer with over 10+ years of experience in designing scalable backend systems using Java, Spring Boot, Microservices, and AWS Cloud. I specialize in building cloud-native applications, integrating DevOps practices, and mentoring teams in writing clean, production-grade code. I created this blog to share real-world backend architecture tips, Spring Boot patterns, and practical coding solutions that help developers grow faster.

JWT stands for JSON Web Token.

Think of it like a sealed envelope:

  • Inside the envelope β†’ JSON data (like user ID, roles, permissions).

  • The seal outside β†’ A signature that proves no one has tampered with the contents.

Anyone can open the envelope and read the data, but only someone with the correct key can create or modify it without breaking the seal.


🚨 Why JWT? β€” The Problem & the Solution

Traditional session-based authentication stores user session data on the server (in memory or Redis). This becomes a bottleneck for stateless APIs and microservices because:

  • Every request must check the central session store.

  • In distributed systems, session sync becomes complex.

  • Scaling horizontally becomes harder.

JWT solves this by embedding authentication & authorization details inside a digitally signed token.
The client stores the token, and the server just verifies it β€” no database lookup needed.

Benefits:

  • βœ… Stateless β€” no server session storage.

  • βœ… Works across services & domains (perfect for SSO & microservices).

  • βœ… Compact & Base64URL-encoded (easy to send in HTTP headers).

  • βœ… Faster request handling β€” no central session DB lookup.


🧩 Anatomy of a JWT

A JWT has three Base64URL-encoded parts, separated by dots:

<Header>.<Payload>.<Signature>

1. Header β€” Meta info

Tells what type of token and which signing algorithm is used.

{
  "alg": "RS256",
  "typ": "JWT"
}

2. Payload β€” Claims (your actual data)

Contains user info, roles, expiry time, etc.

{
  "sub": "user123",
  "role": "ADMIN",
  "exp": 1723640000
}

⚠️ Note: Data in the payload is not encrypted by default, so don’t put sensitive info unless encrypted separately.


3. Signature β€” Integrity proof

The server signs <header>.<payload> using:

  • A secret key (HS256 β€” symmetric)

  • Or a private key (RS256 β€” asymmetric)

Example JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9   // Header
.eyJ1c2VySWQiOjEwMSwicm9sZSI6ImFkbWluIn0  // Payload
.ZU1y3_jyQXYJwD9ncz0rZn7a7gW9MbbZoPSfyTjP9xk  // Signature

πŸ”„ How JWT Works β€” Step-by-Step Lifecycle

  1. User logs in via SSO or username/password.

  2. Authorization server verifies credentials (Okta, Auth0, custom auth).

  3. JWT is created with user data (e.g., userId: 101, role: admin).

  4. Token is signed with secret/private key.

  5. Token is sent to the client (browser or mobile).

  6. Client stores JWT securely (HTTP-only cookie, secure storage).

  7. Client sends JWT on every request in the Authorization header:

     Authorization: Bearer <jwt-token>
    
  8. API verifies token:

    • Checks signature.

    • Checks expiry (exp claim).

    • Reads claims for authorization.

  9. Access is granted or denied.

⚠️ Note*: When JWT expires, the *refresh token is used to request a new JWT without logging in again.


πŸ” HS256 vs RS256 β€” Which to Use?

  • HS256 (HMAC) β†’ Uses the same secret to sign & verify.
    βœ… Simple, but less secure for distributed systems.

  • RS256 (RSA) β†’ Private key signs, public key verifies.
    βœ… More secure & scalable β€” ideal for SSO and microservices.

⚠️ Note*: Okta defaults to RS256 and publishes the public key via *JWKS endpoint (/v1/keys).


πŸ›  Real-World Use Cases

πŸ” Security

  • Stateless authentication for APIs.

  • Role-based access control (RBAC) using claims.

  • Cross-domain SSO with providers like Okta.

  • Mobile app authentication without cookies.

πŸ“‘ Data Transfer

  • Microservice-to-microservice authentication.

  • Temporary access links (e.g., password reset).

  • Embed small metadata to avoid DB lookups.


βš™ Spring Boot Validation Flow

Spring Security + Resource Server validates JWT automatically:

  1. Fetches public key from Okta’s JWKS endpoint (/v1/keys).

  2. Verifies signature using matching key ID (kid).

  3. Validates standard claims (exp, iat, iss, aud).

  4. Maps custom claims (roles, groups) to GrantedAuthority.

Minimal config:

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-xxx.okta.com/oauth2/default

❀️ Why Developers Love JWT

  • Easy to implement.

  • Works across web, mobile, and microservices.

  • No server-side session storage needed.

  • Can be verified offline via signature check.


πŸ“Œ What’s Next?

In the next deep dive, we’ll explore Refresh Tokens β€” the hidden heroes that keep your users logged in without asking for credentials again.
We’ll cover:

  • Structure (Header, Payload, Signature)

  • How they’re generated, signed, and validated

  • Security pitfalls like token theft & replay attacks


πŸ’¬ Feedback?

If you found this useful, leave a comment or connect with me on LinkedIn. πŸš€