BBackend CourseLeroy Labs
0/0
Search the course

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.

● intermediateSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

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

  1. Algorithm matches what you expect (reject alg: none; never trust the header blindly).
  2. Signature is valid.
  3. exp is in the future (allow a little clock skew).
  4. iss (and aud) match.
  5. 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

Spring-Boot-Storefilters/JwtAuthenticationFilter.java · services/JwtService.java

Store 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.

Hostel-Web-Appauth/security/JwtAuthenticationFilter · JwtService

Claims 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.

Report-Manager-2shared/security/JwtUtil.java · JwtAuthenticationFilter

HS512 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.

SperoTek (in dev)identity/infrastructure/NimbusAccessTokens.java · SessionGuardFilter

SperoTek 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.

  • 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. localStorage is readable by any XSS.
  • JWE gives you encrypted JWTs if you really need confidential claims.
  • PASETO is an alternative token format with fewer footguns.

Check yourself

1. Can a user read the claims inside their JWT?
2. Many microservices verifying tokens from one auth server should use…
3. Main advantage of Hostel reloading the user each request?