Definition

  • JWT: JSON Web Token
  • A signed string used to prove “who you are”.

Structure

header.payload.signature
  1. Header: Algorithm, token type
{
  "alg": "HS256",
  "typ": "JWT"
}
  1. Payload: User data, claims
{
  "sub": "12345",
  "name": "Fū",
  "role": "admin",
  "exp": 1732760400
}
  1. Signature: To prevent tampering
HMACSHA256(
    base64url(header) + "." + base64url(payload),
    secret_key
)

Workflow

  1. User login, backend checks credentials
POST /login
{
  "email": "[email protected]",
  "password": "1234"
}
  1. Backend creates a JWT with user info
{
  "token": "xxxxx.yyyyy.zzzzz"
}
  1. Backend sends the JWT to the client
  2. Client stores it (cookie or localStorage)
  3. Client sends JWT in every request
Authorization: Bearer xxxxx.yyyyy.zzzzz
  1. Backend verifies signature, allow or deny request

Pros and Cons?

  • Pros
    • No session storage required (server is stateless)
      • Especially works well in microservices
    • Fast, simple
    • A standard, widely adopted
  • Cons
    • Cannot be revoked easily until expiration
    • Payload is visible, not encrypted