Exploring JSON Web Tokens: Understanding Header, Claims Set, and Signature

Table of Contents

JSON Web Token

A JWT consists of three parts separated by dots: header.payload.signature

Header

The header specifies the token type and signing algorithm:

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

Common algorithms:

  • HS256 - HMAC with SHA-256 (symmetric)
  • RS256 - RSA with SHA-256 (asymmetric)
  • ES256 - ECDSA with P-256 curve

Claims Set (Payload)

The payload contains claims about the entity and additional metadata:

{
    "sub": "1234567890",
    "name": "Alice",
    "email": "alice@example.com",
    "iat": 1516239022,
    "exp": 1516242622,
    "roles": ["user", "admin"]
}

Registered Claims

Claim Description
iss Issuer
sub Subject (user ID)
aud Audience
exp Expiration time
nbf Not before
iat Issued at
jti JWT ID (unique token ID)

Signature

The signature is created by encoding header and payload, then signing:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

Example Token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Implementation

Python

import jwt
from datetime import datetime, timedelta

secret = "your-secret-key"

# Create token
payload = {
    "sub": "user123",
    "exp": datetime.utcnow() + timedelta(hours=1)
}
token = jwt.encode(payload, secret, algorithm="HS256")

# Verify token
decoded = jwt.decode(token, secret, algorithms=["HS256"])

JavaScript

const jwt = require('jsonwebtoken');

const secret = 'your-secret-key';

// Create token
const token = jwt.sign({ userId: '123' }, secret, { expiresIn: '1h' });

// Verify token
const decoded = jwt.verify(token, secret);

Security Considerations

  • Always validate exp claim
  • Use strong secrets (256+ bits)
  • Prefer RS256 for distributed systems
  • Never store sensitive data in payload
  • Implement token revocation for logout

Tools

Author: Jason Walsh

j@wal.sh

Last Updated: 2025-12-21 23:01:09

build: 2025-12-29 20:02 | sha: 3c17632