Sessions vs JWT, and how JWTs actually work
Server sessions vs stateless tokens, JWT structure, HS256/HS512 vs RS256, the claims you need, the authentication filter, and the revocation problem SperoTek solved with server-side sessions.
Two models
| Server session | JWT (stateless token) | |
|---|---|---|
| What the client holds | A random session id (cookie) | A signed token with claims |
| What the server holds | Session data (memory, Redis, DB) | Nothing, except the signing key |
| Lookup per request | Yes (session store) | No, just verify the signature |
| Revocation | Instant (delete the session) | Hard: valid until it expires |
| Scaling | Needs a shared session store | Any instance can verify |
| Mobile / third-party APIs | Clunky | Natural |
JWT anatomy
eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIn0 . eyJzdWIiOiI3ZjMuLi4iLCJyb2xlIjoiU1RVREVOVCIsImV4cCI6MTc2NDA... . 4Xq9...
header (base64url) payload (base64url) signature
{"alg":"HS256","kid":"v1"} {"sub":"7f3...","role":"STUDENT","iss":"hostel","iat":...,"exp":...}
- The payload is encoded, not encrypted. Anyone can read it, so never put secrets or PII you wouldn’t show the user in it.
- The signature proves the token was issued by you and hasn’t been altered.
Algorithms
| Alg | Key | Use |
|---|---|---|
| HS256 / HS512 (all your projects) | One shared secret signs and verifies | A single service that issues and verifies its own tokens |
| RS256 / ES256 / EdDSA | The private key signs, the public key verifies | Many services verify tokens from one issuer (OIDC, microservices); publish keys at a JWKS endpoint |
Verification checklist
- Algorithm matches what you expect (reject
alg: none; never trust the header blindly). - Signature is valid.
expis in the future (allow a little clock skew).iss(andaud) match.- Optionally, the user and session are still active (see below).
Claims claims = Jwts.parser()
.verifyWith(key) // fixed algorithm family via key type
.requireIssuer("hostel")
.build()
.parseSignedClaims(token) // throws on bad signature or expired token
.getPayload();
The filter
public class JwtAuthenticationFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
String token = extractBearer(req); // or from an HttpOnly cookie
if (token != null) {
Claims c = jwtService.parse(token); // parse ONCE
User u = userRepository.findById(UUID.fromString(c.getSubject())).orElse(null);
if (u != null && u.isActive()) {
var auth = new UsernamePasswordAuthenticationToken(new CustomUserDetails(u), null, u.authorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
chain.doFilter(req, res);
}
}
In your projects
filters/JwtAuthenticationFilter.java · services/JwtService.javaStore is the simplest: HS key via Keys.hmacShaKeyFor, and the principal is the user’s UUID with authority "ROLE_" + role, taken from the token without a DB lookup. That’s fast, but a deactivated user or a changed role keeps working until the token expires. It used to parse the token three times per request; Store PR #1 parses it once and reuses the claims.
auth/security/JwtAuthenticationFilter · JwtServiceClaims are sub=userId, email, name and role. The filter reloads the user from the DB on every request and rejects isActive == false. That costs one indexed query per request, and buys instant deactivation.
shared/security/JwtUtil.java · JwtAuthenticationFilterHS512 via JJWT. The token is read from an HttpOnly cookie first, falling back to the Authorization: Bearer header, which supports both the browser and API clients.
identity/infrastructure/NimbusAccessTokens.java · SessionGuardFilterSperoTek uses a hybrid model. Its access tokens are HS256 and carry only the user and session id (decision D-11), with a 15-minute TTL and issuer sperotek-accounting. A SessionGuardFilter checks that the server-side session is still alive. You get JWT’s speed plus session-style revocation: log out, or “sign out other devices”, and the session dies immediately. Permissions are not in the token; they’re resolved per company by TenantResolutionFilter.
Related concepts you must know
- Short access token + long refresh token is the standard pattern (next lesson).
- Where to store tokens in a browser: an HttpOnly cookie (safe from XSS, but needs CSRF thought) or memory.
localStorageis readable by any XSS. - JWE gives you encrypted JWTs if you really need confidential claims.
- PASETO is an alternative token format with fewer footguns.