{# canonical_base is the OWNING tenant's origin: all 16 Peasy domains serve the same catalogue, so a page rendered by a non-owner points its canonical at the owner instead of competing with it. Falls back to this site for static/self-owned pages. #}
🍋
Menu
Comparison Beginner 1 min read 264 words

JWT Token Generation and Structure Explained

JSON Web Tokens (JWT) are the standard for stateless authentication. Understanding their structure, signing algorithms, and security considerations prevents common vulnerabilities.

Key Takeaways

  • A JWT consists of three Base64URL-encoded parts separated by dots:
  • Always validate the `exp` claim server-side
  • If the server accepts `alg: none`, an attacker can forge tokens without a signature.
  • Always whitelist accepted algorithms server-side.
  • Always transmit tokens in the Authorization header or HTTP-only cookies.

JWT Structure

A JWT consists of three Base64URL-encoded parts separated by dots:

header.payload.signature

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

Specifies the signing algorithm and token type.

Payload (Claims)

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1741564800,
  "exp": 1741568400
}

Standard claims: iss (issuer), sub (subject), exp (expiration), iat (issued at), aud (audience), nbf (not before).

Signature

HMAC-SHA256(base64(header) + '.' + base64(payload), secret)

Signing Algorithms

Algorithm Type Key Use Case
HS256 Symmetric Shared secret Single-server apps
RS256 Asymmetric RSA key pair Microservices, third-party verification
ES256 Asymmetric ECDSA key pair Mobile apps (smaller keys)
none No signature NEVER use (vulnerability)

Security Best Practices

  • Always validate the exp claim server-side
  • Use short expiration times (15 minutes for access tokens)
  • Use refresh tokens for re-authentication
  • Never store sensitive data in the payload (it is only Base64 encoded, not encrypted)
  • Reject tokens with alg: none
  • Validate the iss and aud claims

Common Vulnerabilities

Algorithm Confusion

If the server accepts alg: none, an attacker can forge tokens without a signature. Always whitelist accepted algorithms server-side.

Excessive Token Lifetime

Long-lived tokens (hours or days) give attackers a wide window if stolen. Use short-lived access tokens + refresh token rotation.

Token in URL Parameters

JWTs in URLs appear in server logs, browser history, and Referer headers. Always transmit tokens in the Authorization header or HTTP-only cookies.