JWT Security Best Practices
Hi there! I’m Maneshwar. Currently, I’m building a private AI code review tool that runs on your LLM key (OpenAI, Gemini, etc.) with flat, no-seat pricing — designed for small teams. Check it out, if that’s your kind of thing.
JSON Web Tokens (JWT) are widely used for stateless authentication in modern APIs and applications.
While powerful, they can also become a major security liability if not handled properly.
Here are some best practices you should follow to keep your JWT-based auth system secure.
Use a Strong JWT Secret
A weak or predictable secret can lead to token forgery. Your JWT secret should be:
- Long and random
- Cryptographically secure
- Stored safely (e.g., in a secrets manager)
- Rotated periodically
This helps prevent brute-force attacks and ensures token integrity.
Don’t Trust JWT Header Algorithms
Never rely on the algorithm declared in the JWT header. Attackers can tamper with it to downgrade to a weaker algorithm like none
or HS256
. Instead, force a fixed algorithm like RS256
or HS256
server-side during token verification.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Force algorithm
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
return []byte(secret), nil
})
Set a Reasonable Expiry
Tokens should have short lifetimes to reduce the blast radius if compromised. Use exp
and iat
claims to control TTL and refresh window.
claims := jwt.MapClaims{
"sub": "user_id",
"exp": time.Now().Add(15 * time.Minute).Unix(),
"iat": time.Now().Unix(),
}
Combine this with short-lived access tokens and longer-lived refresh tokens for better usability and security.
Don’t Store Sensitive Data in the Payload
JWTs are not encrypted by default — they are base64-encoded and can be decoded by anyone with access to them. Never put:
- Passwords
- Access keys
- PII or confidential data
Instead, keep it minimal: user ID, scopes, and basic claims.
Keep the Payload Lightweight
Large JWT payloads cause:
- Increased network latency
- Longer processing times
- Higher risk of DoS if abused
Stick to essential claims only. If you need more data, fetch it from a secure source using the token.
By following these JWT security best practices, you can avoid common pitfalls and reduce your attack surface, keeping both your users and systems safe.
LiveReview helps you get great feedback on your PR/MR in a few minutes.
Saves hours on every PR by giving fast, automated first-pass reviews. Helps both junior/senior engineers to go faster.
If you’re tired of waiting for your peer to review your code or are not confident that they’ll provide valid feedback, here’s LiveReview for you.