JSON Web Tokens are widely used for authentication.
They're also widely misunderstood.
A JWT is not automatically more secure than sessions.
It is simply a token format with specific properties.
Basic JWT Structure
A JWT commonly consists of three sections:
Header.Payload.Signature
For example:
xxxxx.yyyyy.zzzzz
The payload can contain claims:
{
"sub": "12345",
"role": "user"
}
Important: JWT Payloads Are Not Secret
JWT contents are typically encoded, not encrypted.
Therefore, don't place sensitive information inside them.
For example, avoid putting:
{
"password": "secret123"
}
in a JWT.
Authentication Flow
A common flow is:
User logs in
↓
Server validates credentials
↓
Server issues token
↓
Client sends token with requests
↓
Server validates token
Token Expiration
Tokens should generally have appropriate expiration periods.
Short-lived access tokens can reduce the impact of token theft.
Some architectures also use refresh tokens to obtain new access tokens.
Storage Matters
Where tokens are stored affects security.
Developers should understand the risks of:
- XSS
- CSRF
- Token theft
- Insecure browser storage
- Long-lived tokens There isn't a universal storage strategy that is correct for every architecture.
JWT Isn't a Session Replacement by Default
Traditional server-side sessions can be simpler for many applications.
The right choice depends on requirements.
Final Thoughts
Learn JWT as an authentication mechanism, not as a security buzzword.
The important questions are:
Where is the token stored?
How long does it live?
How is it revoked?
How are requests authenticated?
Top comments (0)