Back to 20 Concepts
jwt-tokensAdvanced

JSON Web Tokens (JWT): Header, Payload Claims & RS256 vs HS256

JWTs encode claims into 3 Base64URL-encoded segments separated by dots: Header.Payload.Signature. HS256 uses a symmetric shared secret, while RS256 uses an asymmetric private key to sign and a public key (JWKS) to verify across microservices.

Intuitive Mental Model

The Notarized Government Passport: The passport lists your photo and birthdate (Payload Claims). The government notary stamps it with an embossed wax seal (RS256 Digital Signature). Any border officer worldwide can verify the seal using the public notary stamp without calling headquarters.

Architecture Blueprint & CodeProduction Standard
// JWT Format: [Base64Header].[Base64Payload].[Signature]

// Header: { "alg": "RS256", "typ": "JWT", "kid": "key_2026_01" }
// Payload: { "sub": "usr_942", "role": "admin", "exp": 1723650000, "iss": "https://auth.corp.io" }

// Node.js Verification with RS256 Public Key:
import jwt from 'jsonwebtoken';

function verifyAccessToken(token: string, publicKeyPem: string) {
  return jwt.verify(token, publicKeyPem, {
    algorithms: ['RS256'], // Explicitly whitelist algorithm!
    issuer: 'https://auth.corp.io',
    audience: 'https://api.corp.io'
  });
}

Key Architectural Takeaways

  • Stateless Verification: Microservices verify RS256 signatures locally using cached public keys without querying the auth database.
  • Standard Claims: sub (subject), iss (issuer), aud (audience), exp (expiration time), nbf (not before).
  • RS256 vs HS256: RS256 allows downstream microservices to verify tokens without trusting them with the private signing secret.
Common Architectural Pitfall

Failing to whitelist algorithms during verification, allowing attackers to forge tokens with "alg": "none" or swap RS256 public keys into HS256 secrets.

Production Best Practice

Explicitly enforce { algorithms: ["RS256"] } during jwt.verify().