DEV Community

Cover image for 🔐 Understanding JWT (JSON Web Tokens)
Ankit chaurasiya
Ankit chaurasiya

Posted on

🔐 Understanding JWT (JSON Web Tokens)

A Developer's Essential Guide What is JWT?

JSON Web Token (JWT) is a compact, URL-safe token format used for securely transmitting information between parties.

Think of it as a digital passport that carries user credentials and claims in a standardised, verifiable format.

🔄 JWT Workflow:
1️⃣ Login Request → User provides credentials

2️⃣ JWT Issued → Server validates and responds with a token

3️⃣ Client Stores JWT → Usually in localStorage or sessionStorage

4️⃣ Authenticated Requests → JWT is sent in Authorisation: Bearer

5️⃣ Server Verifies & Responds

How is JWT Created?

A JWT consists of three parts separated by dots (.):

🔹 Header: Contains token type (JWT) and signing algorithm (e.g., HS256, RS256)

🔹 Payload: Contains claims (user data, permissions, expiration)

🔹 Signature: Ensures token integrity using a secret key or certificate

Structure: header.payload.signature

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFua2l0IiwiaWF0IjoxNjg4MDA2NDc1fQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Enter fullscreen mode Exit fullscreen mode

🔍 JWT Payload Breakdown (Middle Part):

This is a Base64-encoded JSON and may look like this:

{ 
"sub": "1234567890", // Subject (user ID) 
"name": "Ankit", // User name 
"iat": 1688006475, // Issued At (timestamp)
"exp": 1688010075, // Expiration time (optional) 
"role": "admin" // Custom claim 
}
Enter fullscreen mode Exit fullscreen mode

Payload Information:
The payload contains "claims" - statements about the user and
additional data:
• Registered Claims: Standard fields like iss (issuer), exp (expiration), sub (subject)

• Public Claims: Custom fields defined in JWT registry

• Private Claims: Application-specific data like user roles, permissions

Key Benefits:

✅ Stateless: No server-side session storage needed

✅ Scalable: Perfect for micro services and distributed systems

✅ Secure: Cryptographically signed and optionally encrypted

✅ Cross-platform: Works across different domains and applications

Important Considerations:

⚠️ Size: JWTs can become large with extensive payload data

⚠️ Security: Never store sensitive data in payload (it's Base64 encoded, not encrypted)

⚠️ Expiration: Always set appropriate expiration times

⚠️ Storage: Store securely (httpOnly cookies preferred over localStorage)

Common Use Cases:

🎯 Authentication and authorization

🎯 Single Sign-On (SSO)

🎯 API security

🎯 Information exchange between services

Pro Tips: 💡 Use short expiration times with refresh tokens 💡 Implement proper token revocation strategies 💡 Always validate tokens on the server side applications?

Share your experiences below! 👇

JWT #WebDevelopment #Authentication #Security #API #WebTokens #Programming

Top comments (0)