Concept Explanation
Traditional sessions store login state on the server: the client holds a session id, the server holds the data. That works until you run five instances behind a load balancer and each has a different memory.
A JWT (JSON Web Token) inverts this. The server signs a token containing the user's identity and hands it over. The client sends it with every request. The server stores nothing — it just verifies the signature.
Anatomy
Three base64 sections joined by dots:
eyJhbGciOiJIUzI1NiJ9 . eyJzdWIiOiJoYXJzaCIsInJvbGUiOiJVU0VSIn0 . 4pQd...
header payload signature
- Header — the algorithm, e.g.
HS256. - Payload — claims:
sub(subject),exp(expiry), plus your own. - Signature — proof the payload was not altered.
The payload is encoded, not encrypted. Anyone can read it. Never put a password, card number, or anything private in a JWT.
Issuing a Token
@Service
public class JwtService {
private final SecretKey key; // from configuration, never hard-coded
public JwtService(@Value("${app.jwt.secret}") String secret) {
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
public String issue(String username, List<String> roles) {
Instant now = Instant.now();
return Jwts.builder()
.subject(username)
.claim("roles", roles)
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(15, ChronoUnit.MINUTES)))
.signWith(key)
.compact();
}
public String verifyAndGetSubject(String token) {
return Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token) // throws if tampered or expired
.getPayload()
.getSubject();
}
}
Using It
The client sends the token in a header:
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
A filter validates it once per request and populates the security context:
@Component
public class JwtFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws Exception {
String header = req.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
try {
String user = jwtService.verifyAndGetSubject(header.substring(7));
var auth = new UsernamePasswordAuthenticationToken(
user, null, List.of());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException ignored) {
// invalid token — leave the context empty, Spring returns 401
}
}
chain.doFilter(req, res);
}
}
The Revocation Problem
A signed token is valid until it expires. You cannot "log someone out" server-side without extra machinery. The standard answer is two tokens:
- Access token — short-lived (15 minutes), sent with every request.
- Refresh token — long-lived, stored server-side, exchanged for new access tokens and revocable.
That way a compromised access token expires quickly, and revoking the refresh token ends the session.
Common Mistakes
- Secrets in source control: A leaked signing key lets anyone mint valid tokens for any user. Read it from the environment.
- Long-lived access tokens: A 30-day token that leaks is a 30-day breach.
- Storing tokens in
localStorage: Readable by any XSS payload. AnHttpOnlycookie is safer. - Sensitive data in the payload: It is public. Treat it as such.
- Accepting
alg: none: A historic vulnerability class — always verify with your expected algorithm.
Best Practices
- Short access tokens plus revocable refresh tokens.
- A strong random secret (256 bits or more), injected from configuration.
- HTTPS only — a bearer token is a password in transit.
- Keep claims minimal: username and roles. Look up everything else.
Practice Exercises
- The Decode: Issue a token, paste it into jwt.io, and read the payload. Explain why this proves you must not put secrets in it.
- The Tampered Token: Change one character in the payload section and confirm verification fails.
- The Expiry: Issue a token valid for 10 seconds. Call a protected endpoint before and after it expires.