Practice: JWT authentication
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Before shipping a JWT login, check the same short list every time: what is in the payload, how long the token lives, which algorithm the server trusts, where roles go and what happens to a reused refresh token.
Decoding tokens and spotting dangerous claims
Reading a token is the first step of any JWT debugging session: which algorithm, which subject, which roles, and is exp there at all? The program below decodes three tokens and flags what is dangerous.
Example 1 · TokenAudit: decode and flag dangerous claims
import java.nio.charset.StandardCharsets;import java.util.Base64;import java.util.List;
/** Decodes a token's header and payload and flags claims that should never be in a JWT. */public class TokenAudit {
static final List<String> NEVER = List.of("password", "otp", "cardNumber", "aadhaar"); static final List<String> PERSONAL = List.of("email", "phone", "address", "dob");
static String decode(String part) { return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8); }
static void audit(String name, String token) { String[] parts = token.split("\\.", -1); String header = decode(parts[0]); String payload = decode(parts[1]); System.out.println(name + ": " + header + " " + payload); if (header.contains("\"alg\":\"none\"") || parts[2].isEmpty()) { System.out.println(" DANGER unsigned token (alg none or empty signature)"); } for (String claim : NEVER) { if (payload.contains("\"" + claim + "\"")) { System.out.println(" DANGER secret in payload: " + claim); } } for (String claim : PERSONAL) { if (payload.contains("\"" + claim + "\"")) { System.out.println(" WARNING personal data in payload: " + claim); } } if (!payload.contains("\"exp\"")) { System.out.println(" DANGER no exp: valid forever"); } }
static String part(String json) { return Base64.getUrlEncoder().withoutPadding().encodeToString(json.getBytes(StandardCharsets.UTF_8)); }
public static void main(String[] args) { String hs = part("{\"alg\":\"HS256\"}"); audit("Token A", hs + "." + part("{\"sub\":\"2\",\"roles\":[\"CUSTOMER\"],\"exp\":1792138389}") + ".c2ln"); audit("Token B", hs + "." + part("{\"sub\":\"2\",\"email\":\"asha.rao@example.com\",\"password\":\"asha-dev-password\",\"exp\":1792138389}") + ".c2ln"); audit("Token C", part("{\"alg\":\"none\"}") + "." + part("{\"sub\":\"1\",\"roles\":[\"ADMIN\"]}") + "."); }}Token A: {"alg":"HS256"} {"sub":"2","roles":["CUSTOMER"],"exp":1792138389}
Token B: {"alg":"HS256"} {"sub":"2","email":"asha.rao@example.com","password":"asha-dev-password","exp":1792138389}
DANGER secret in payload: password
WARNING personal data in payload: email
Token C: {"alg":"none"} {"sub":"1","roles":["ADMIN"]}
DANGER unsigned token (alg none or empty signature)
DANGER no exp: valid foreverWhat this code does
- Token A is ShopLite's shape: an id, roles and an expiry, nothing else to worry about.
- Token B leaks the password to anyone who sees it; changing the password is the only fix once it was issued.
- Token C is the alg none attack with no expiry: a server with a fixed algorithm rejects it before reading the claims.
Then look for what must not be there. Secrets (password, OTP, card number, Aadhaar) are a leak the moment the token is issued. Personal data (e-mail, phone, address) is readable by every proxy and browser extension that sees the token. An unsigned token or a missing exp is a hole in the server, not just in the token.
Fixing broken JWT configuration
Review SecurityConfig, JwtConfig and TokenService for five things. The class below has all five mistakes, and each one passes a quick manual test with a fresh token.
Example 2 · A JWT configuration with five mistakes
Runs in: a code review of a Spring Boot 4.1 project
@Configurationclass SecurityConfig {
@Bean SecurityFilterChain chain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/api/v1/auth/login").permitAll() .anyRequest().authenticated()) .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults())) .csrf(csrf -> csrf.disable()); return http.build(); }
@Bean JwtDecoder jwtDecoder() { SecretKey key = new SecretKeySpec("shoplite".getBytes(), "HmacSHA256"); NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(key).build(); decoder.setJwtValidator(new JwtIssuerValidator("shoplite-api")); return decoder; }}
// and in TokenServiceJwtClaimsSet claims = JwtClaimsSet.builder() .issuer("shoplite-api").subject(user.getUsername()) .issuedAt(now).claim("roles", roles).build();BUG 1 `oauth.jwt(Customizer.withDefaults())`: hasRole("ADMIN") is always 403, the default converter reads "scope" as SCOPE_...
Fix: jwt.jwtAuthenticationConverter(rolesFromToken()) with claim "roles" and prefix "ROLE_".
BUG 2 `csrf.disable()` with no sessionManagement: Spring may still keep the SecurityContext in an HttpSession and send JSESSIONID.
Fix: sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).
BUG 3 `new SecretKeySpec("shoplite".getBytes(), ...)`: a secret in Git, and 8 bytes can be brute-forced from any token.
Fix: JwtProperties with a 32-byte Base64 secret from JWT_SECRET, checked at startup.
BUG 4 `setJwtValidator(new JwtIssuerValidator(...))` replaces the defaults: expired tokens are accepted.
Fix: DelegatingOAuth2TokenValidator(JwtTimestampValidator(skew), JwtIssuerValidator(issuer)).
BUG 5 `.subject(user.getUsername())` and no `expiresAt`: personal data in a readable payload, and a token that never expires.
Fix: subject(String.valueOf(user.getId())) and expiresAt(now.plus(accessTokenTtl)).What this code does
- Bugs 1, 2 and 4 sit in the security setup, bugs 3 and 5 in key and claim handling; ShopLite's
SecurityConfig,JwtConfig,JwtPropertiesandTokenServiceshow each fix. - A fresh token for a customer passes every manual test with this code, which is why reviews and negative tests matter.
- Fix them in this order: key first (3), then the decoder (4), then claims (5), then the chain (1, 2).
The five checks: roles become ROLE_ authorities, sessions are STATELESS, the key is long and comes from the environment, the validator list still contains the timestamp check, and the claims have an id subject and an expiresAt. None of these bugs stops the app from starting, which is why ShopLite has tests for an expired token, a token signed with another key and a customer token on an admin URL.
Tracing a login and an authenticated request with curl
A trace follows one user through the whole flow and checks the status at each step. The commands below run a login, /me, an admin URL, a refresh and a reuse.
Example 3 · The full trace for one user
Runs in: the shoplite-api Spring Boot project
B=http://localhost:8080/api/v1# 1. log incurl -s -X POST $B/auth/login -H "Content-Type: application/json" \ -d '{"email":"asha.rao@example.com","password":"asha-dev-password"}'# 2. use the access tokencurl -s $B/me -H "Authorization: Bearer $ACCESS"# 3. try an admin-only URLcurl -s -o /dev/null -w "%{http_code}\n" $B/customers/1 -H "Authorization: Bearer $ACCESS"# 4. refresh, then reuse the old refresh tokencurl -s -X POST $B/auth/refresh -H "Content-Type: application/json" -d "{\"refreshToken\":\"$REFRESH\"}"curl -s -X POST $B/auth/refresh -H "Content-Type: application/json" -d "{\"refreshToken\":\"$REFRESH\"}"{"accessToken":"eyJraWQiOiJVVWFwcy1CaDlC...CLeQ-8","tokenType":"Bearer","expiresIn":900,"refreshToken":"Olw-UZp3R4h5yifGkTn_UxXAt5KgZhtGvCgJB4OqwAU"}
{"id":2,"email":"asha.rao@example.com","fullName":"Asha Rao","customerId":1,"roles":["CUSTOMER"]}
403
{"accessToken":"eyJraWQiOiJVVWFwcy1CaDlC...mNn0o","tokenType":"Bearer","expiresIn":900,"refreshToken":"rg-JklP8sOyF4GNvadIv84T6VU6ANh1OPK5nh7tp6Qs"}
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The refresh token is invalid or has expired. Sign in again.","instance":"/api/v1/auth/refresh"}What this code does
- Each line is one step: tokens, my data, 403 on an admin URL, a rotated refresh token, then 401 for the reused old one.
- The shell variables hold the tokens from step 1 (
ACCESS,REFRESH); tokens are shortened with...here. - A different status at any step points to the code: 401 at step 2 is the decoder, 403 expected at step 3 is the role rule, 200 at the last step would mean no rotation.
Expect: login 200 with two tokens, /me 200 with the access token, an admin URL 403, refresh 200 with a new refresh token, and the old refresh token 401. When a step answers something else, the WWW-Authenticate header and the server log say why.
Run the trace after every change to the security code. It takes a minute and catches bugs that unit tests with mocked security miss, such as a missing permitAll for /auth/refresh.
Interview drill: JWT vs sessions, refresh tokens and logout
Interviewers ask about JWTs to see whether you know the trade-offs, not just the annotations. The Interview tab has the drill; prepare a short answer for each topic below.
Cover: what is inside a JWT and who can read it; how the server checks it; why access tokens are short; how logout works when tokens are stateless; why refresh tokens rotate; where a browser should keep tokens; and when you would pick sessions instead.
Answer with ShopLite's real numbers and names: 15-minute HS256 access tokens checked by NimbusJwtDecoder, 7-day refresh tokens stored as SHA-256 hashes, rotation with family revocation, and sessions for the server-rendered admin console.
Finish up
Mark complete & continue
Next: Mini project: JWT login for ShopLite