Featured
8 min read

Understanding JWT Tokens

A comprehensive guide to JSON Web Tokens (JWT) - how they work, their structure, and best practices for implementation.

Zain Shaikh
January 10, 2024
8 min read
jwt
authentication
security
api

Understanding JWT Tokens

JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. They're commonly used for authentication and authorization in web applications.

What is a JWT?

A JWT is a self-contained token that contains information about the user and their permissions. It consists of three parts separated by dots:

  1. Header: Contains metadata about the token
  2. Payload: Contains the actual data (claims)
  3. Signature: Verifies the token hasn't been tampered with

JWT Structure

A typical JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Header

The header contains metadata about the token:

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

Payload

The payload contains the claims (data):

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Common Claims

  • iss (Issuer): Who issued the token
  • sub (Subject): Who the token is about
  • aud (Audience): Who the token is intended for
  • exp (Expiration Time): When the token expires
  • iat (Issued At): When the token was issued

Security Best Practices

  1. Use HTTPS: Always transmit JWTs over HTTPS
  2. Set Expiration: Always set an expiration time
  3. Keep Secrets Safe: Store signing keys securely
  4. Validate Tokens: Always validate tokens on the server
  5. Use Appropriate Algorithms: Choose secure signing algorithms

Implementation Example

Creating a JWT (Node.js):

const jwt = require('jsonwebtoken');

const payload = {
  userId: 123,
  email: 'user@example.com',
  role: 'admin'
};

const token = jwt.sign(payload, 'your-secret-key', { expiresIn: '1h' });
console.log(token);

Verifying a JWT:

try {
  const decoded = jwt.verify(token, 'your-secret-key');
  console.log(decoded);
} catch (error) {
  console.error('Invalid token');
}

When to Use JWTs

Good Use Cases:

  • Stateless authentication
  • API authentication
  • Single Sign-On (SSO)
  • Microservices communication

Avoid Using For:

  • Storing sensitive data (tokens are not encrypted)
  • Session management (use secure sessions instead)
  • Large amounts of data (tokens should be compact)

Conclusion

JWTs are powerful tools for authentication and authorization, but they must be used correctly and securely. Understanding their structure and best practices is crucial for building secure applications.

Try our JWT Decoder to explore JWT tokens!