Definition#
- JWT: JSON Web Token
- A signed string used to prove “who you are”.
Structure#
header.payload.signature
- Header: Algorithm, token type
{
"alg": "HS256",
"typ": "JWT"
}
- Payload: User data, claims
{
"sub": "12345",
"name": "Fū",
"role": "admin",
"exp": 1732760400
}
- Signature: To prevent tampering
HMACSHA256(
base64url(header) + "." + base64url(payload),
secret_key
)
Workflow#
- User login, backend checks credentials
POST /login
{
"email": "[email protected]",
"password": "1234"
}
- Backend creates a JWT with user info
{
"token": "xxxxx.yyyyy.zzzzz"
}
- Backend sends the JWT to the client
- Client stores it (cookie or localStorage)
- Client sends JWT in every request
Authorization: Bearer xxxxx.yyyyy.zzzzz
- 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