Fairplay Interview Prep
Module 05

Spring Security, JWT and refresh tokens

Security questions are where interviewers find out whether you copied a tutorial or understood it. Arena implements stateless JWT authentication, role-based authorisation in three layers, bcrypt passwords, and refresh-token rotation with reuse detection, which many production systems get wrong. This module explains each piece from first principles.

P1 (issues and verifies)P2 (service client)P3 (service client)· about 2 hours

By the end you can answer

  • "Authentication vs authorisation?"
  • "How should passwords be stored? Why bcrypt and not SHA-256?"
  • "What is inside a JWT? Is it encrypted? HS256 vs RS256?"
  • "Sessions vs tokens? Why is CSRF disabled?"
  • "How does Spring Security process a request with a bearer token?"
  • "Why two tokens? How does refresh-token rotation and reuse detection work?"
  • "How can you revoke a JWT?"

1. Authentication vs authorisation

Analogy: an office building

At reception you show ID and get a visitor badge: that's authentication, and the badge is your token. Each door's card reader checks whether your badge opens that door: authorisation. The badge expires at 6 pm (the access token's 15 minutes). Reception stamps each badge (the signature) so a home-made one is rejected. You don't go back to reception for every door; doors trust the stamp. That is "stateless".

Arena has three roles: PLAYER (normal users), MODERATOR (humans who review and decide appeals) and SERVICE (machine accounts: telemetry-sim and judge-agent). AccountSeeder, an ApplicationRunner, creates the moderator and service accounts at startup if they don't exist, with passwords from environment variables. Credentials are never hard-coded.

2. Storing passwords: bcrypt

Never store passwords in plain text, and never "encrypt" them (encryption is reversible, so whoever holds the key gets every password). Store a one-way hash, and at login hash the attempt and compare.

But a plain fast hash like SHA-256 is wrong for passwords. GPUs compute billions of SHA-256 hashes per second, so leaked hashes of human-chosen passwords fall quickly to dictionary and brute-force attacks. Password hashing must be:

  1. Salted: a random value per password is mixed in, so identical passwords produce different hashes and precomputed "rainbow tables" are useless.
  2. Deliberately slow, with a tunable work factor, so each guess costs the attacker real time.

bcrypt does both. Arena's SecurityConfig declares new BCryptPasswordEncoder() (default cost 10, meaning 210 rounds of key expansion). A bcrypt hash looks like $2a$10$N9qo8uLOickgx2ZMRZoMye...: algorithm version, cost, then 22 characters of salt and the hash. The salt is stored inside the string, so no separate column is needed. That is why the password_hash column is VARCHAR(100).

In your projects: you felt the cost

Registering 1,000 simulated players took about a minute, mostly bcrypt on Arena's side. That is the work factor doing its job. It's also why the simulator's registrar caps itself at 16 concurrent registrations: bcrypt is CPU-bound, so more parallelism would only overload Arena. Arena's benchmark seed script inserts a pre-computed bcrypt hash (<BCRYPT_HASH>) for its million rows instead of hashing a million times.

Deep detail that impresses

AuthService.login returns the same INVALID_CREDENTIALS message whether the username doesn't exist or the password is wrong, so attackers can't use error messages to discover valid usernames. A subtle remaining leak is timing: for an unknown user no bcrypt check runs, so the answer comes back faster. A hardening step is to run a dummy bcrypt comparison for unknown users. Mentioning this shows real depth. (Argon2id is the newer recommendation; bcrypt is still widely accepted.)

3. Sessions vs tokens

Server sessions (classic)Bearer tokens (Arena)
After login the client holdsA random session id in a cookieA signed token (a JWT)
The server storesThe session (user, roles) in memory or RedisNothing per request: the token is self-contained
Scaling to many instancesNeeds sticky sessions or a shared session storeAny instance can verify any token
RevocationEasy: delete the sessionHard: valid until it expires (section 8)
Typical useServer-rendered web appsAPIs, mobile apps, service-to-service

Arena sets SessionCreationPolicy.STATELESS: Spring Security never creates an HTTP session, and every request must carry Authorization: Bearer <token>.

4. JSON Web Tokens

A JWT is three Base64url-encoded parts separated by dots: header.payload.signature.

// header
{ "alg": "HS256" }
// payload ("claims") as issued by TokenService.issueAccessToken
{
  "iss": "fairplay-arena",                     // issuer
  "sub": "6f1c2a9e-...-player-uuid",           // subject: who this token is about
  "iat": 1763560000,                           // issued at (epoch seconds)
  "exp": 1763560900,                           // expires at: 15 minutes later
  "username": "alice",
  "roles": ["PLAYER"],
  "typ": "access"                              // custom: only access tokens are accepted
}
// signature = HMAC-SHA256( base64url(header) + "." + base64url(payload), secret )
The most common misconception

A signed JWT is not encrypted. Anyone can Base64-decode the payload and read it (paste one into jwt.io). The signature only proves it was issued by someone holding the key and was not modified. Never put secrets or sensitive personal data in a JWT. Arena's claims are an id, a username, roles and a type.

Verifying a token

The server recomputes the signature with its key and compares, then checks the claims. Arena's JwtConfig builds the decoder:

arena/.../config/JwtConfig.java
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(key)
        .macAlgorithm(MacAlgorithm.HS256)            // accept only HS256
        .build();
OAuth2TokenValidator<Jwt> accessOnly = jwt ->
        "access".equals(jwt.getClaimAsString("typ"))
                ? OAuth2TokenValidatorResult.success()
                : OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token", "Not an access token", null));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
        JwtValidators.createDefaultWithIssuer(props.jwt().issuer()),   // exp/nbf (with clock skew) + iss
        accessOnly));

HS256 vs RS256

HS256 (HMAC, symmetric)RS256 / ES256 (asymmetric)
KeysOne shared secret signs and verifiesA private key signs; a public key verifies
Who can verifyOnly holders of the secret, who could also forge tokensAnyone with the public key (published as a JWKS endpoint); they cannot forge
Fits whenThe same service issues and verifies (Arena)A central auth server issues and many services verify (OAuth2/OIDC: Keycloak, Auth0, Cognito)

Arena both issues and verifies its tokens, so HS256 with a secret of at least 32 bytes (256 bits, enforced by @Size(min = 32)) is appropriate. If Telemetry and the Judge had to verify tokens themselves, RS256 would be the right switch, so only Arena holds a signing key.

5. How Spring Security processes a request

 request ─► Servlet filter chain
              └─ FilterChainProxy (Spring Security) ─ picks the SecurityFilterChain bean
                   ├─ ... (CSRF disabled, no session)
                   ├─ BearerTokenAuthenticationFilter
                   │     reads "Authorization: Bearer xyz"
                   │     ─► JwtAuthenticationProvider ─► JwtDecoder: signature, exp, iss, typ
                   │     ─► JwtAuthenticationConverter: claim "roles":["SERVICE"] → authority ROLE_SERVICE
                   │     ─► stores the Authentication in the SecurityContext (for this request's thread)
                   │     (failure → ProblemAuthenticationEntryPoint → 401 ProblemDetail)
                   ├─ AuthorizationFilter: URL rules (permitAll / authenticated)
                   │     (failure → 401 if anonymous, 403 via ProblemAccessDeniedHandler)
                   ▼
              DispatcherServlet ─► @PreAuthorize("hasRole('SERVICE')") on the method ─► controller
arena/.../config/SecurityConfig.java
http.csrf(csrf -> csrf.disable())
    .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    .authorizeHttpRequests(auth -> auth
        .requestMatchers(HttpMethod.POST, "/api/v1/auth/**").permitAll()                 // register, login, refresh
        .requestMatchers(HttpMethod.GET, "/api/v1/leaderboard", "/api/v1/leaderboard/**").permitAll()
        .requestMatchers("/actuator/health/**", "/actuator/prometheus",
                         "/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
        .anyRequest().authenticated())                                                    // deny by default
    .oauth2ResourceServer(rs -> rs.jwt(jwt -> jwt.jwtAuthenticationConverter(converter))
                                  .authenticationEntryPoint(entryPoint))
    .exceptionHandling(ex -> ex.authenticationEntryPoint(entryPoint)
                               .accessDeniedHandler(deniedHandler));

Notice the shape: a short allow-list of public paths, then anyRequest().authenticated(). Deny by default means a new endpoint is protected even if someone forgets to configure it.

Arena reuses Spring's OAuth2 Resource Server support for JWT verification even though there is no external OAuth server. That gives a battle-tested filter, decoder and error handling instead of a hand-written JWT filter, which is a common source of security bugs.

Roles and authorities

Internally Spring works with authorities (strings). A role is an authority with the prefix ROLE_. JwtAuthenticationConverter reads the roles claim and adds the prefix, so ["SERVICE"] becomes ROLE_SERVICE, and hasRole('SERVICE') checks for ROLE_SERVICE. hasAuthority('ROLE_SERVICE') is the same check written longhand. Mixing them up is a classic bug that silently makes every check fail with 403.

6. Authorisation in three layers

LayerMechanismExample
1. URLauthorizeHttpRequestsLeaderboard GETs are public; everything else needs a valid token
2. Method@EnableMethodSecurity + @PreAuthorizePOST /matches: hasRole('SERVICE'); GET /moderation/queue: hasRole('MODERATOR'); GET /players: hasAnyRole('MODERATOR','SERVICE')
3. Business rulesCode in servicesA suspended player can't edit their profile (403 ACCOUNT_SUSPENDED); moderators must use source HUMAN; services must use TELEMETRY/JUDGE; a service BAN needs confidence ≥ 0.80; only a BANNED player may appeal

Role checks answer "may this kind of caller do this?". Business rules answer "may this caller do this to this resource right now?". Many real breaches (Broken Access Control is #1 in the OWASP Top 10) come from checking only the first. For example, PATCH /players/me takes the player id from the token's sub, never from the URL, so you cannot edit someone else.

In your projects: least privilege for the AI

The Judge logs in as judge-agent. Even if the Judge were fully compromised, Arena would still refuse a ban below 0.80 confidence, refuse an illegal state transition, refuse a non-JUDGE source, and record everything in an append-only log. Giving automated callers a narrow, server-enforced set of permissions is the security story of the whole platform.

7. CSRF and CORS

CSRF (cross-site request forgery): if you are logged into bank.com with a cookie, a malicious site can make your browser submit a form to bank.com, and the browser automatically attaches the cookie. CSRF tokens defend against that.

Arena disables CSRF protection, which is correct for its design: authentication is a bearer token in the Authorization header, and browsers never attach that header automatically to cross-site requests. If you ever stored the JWT in a cookie, you'd need CSRF protection back (or SameSite cookies).

CORS (cross-origin resource sharing) is the browser rule that blocks JavaScript on one origin from reading responses from another, unless the server allows it with Access-Control-Allow-Origin headers. Arena has no browser frontend, so it configures none. A web UI on another domain would need an explicit, narrow CORS configuration. Never use * together with credentials.

8. Access tokens, refresh tokens, rotation and reuse detection

The dilemma

A JWT can't be revoked before it expires, because the server keeps no state. So a long expiry is dangerous (a stolen token works for days), and a short one is annoying (log in every 15 minutes). The standard answer is two tokens:

Access tokenRefresh token
FormSigned JWTOpaque random string: 32 bytes from SecureRandom, Base64url
Lifetime15 minutes7 days
SentOn every API callOnly to POST /auth/refresh
Server stateNone (verify the signature)A row in refresh_tokens, storing only its SHA-256 hash
RevocableNo (it just expires soon)Yes (set revoked_at)

Why hash refresh tokens, and why SHA-256 is fine here

If the database leaks, stored refresh tokens would let an attacker log in as everyone. Storing only SHA-256(token) means the leak is useless. Unlike passwords, a refresh token is 256 bits of randomness, so brute-forcing it from its hash is impossible even with a fast hash. A fast hash is also what lets the server look the token up by hash through a unique index in one query. (Passwords are low-entropy and human-chosen, so they need a slow hash; random tokens don't.)

Rotation

Every successful refresh revokes the presented token and issues a new pair. The old row gets revoked_at = now and replaced_by = newId, which forms a chain. A refresh token is therefore meant to be single-use.

The gap under concurrency (know this before an interviewer finds it)

"Single-use" only holds for requests that arrive one after another. AuthService.refresh reads the token without a row lock, and RefreshToken has no @Version. Two refreshes with the same token that arrive at the same moment can both see "not revoked", both issue a new pair, and the second UPDATE just overwrites replaced_by. The result is two valid token families, and reuse detection never fires. The fix: make revocation conditional, UPDATE refresh_tokens SET revoked_at = :now WHERE id = :id AND revoked_at IS NULL, and treat "0 rows updated" as reuse (or lock the row with @Lock(PESSIMISTIC_WRITE), or add @Version). Prove it with a latch-based test that fires two refreshes together. Module 16, section 2.1 has the full analysis.

Reuse detection

If a token that was already used (revoked) is presented again, then either an attacker stole it and used it first, or the attacker is using it now after the real user rotated. The server can't tell which. Both mean the token family is compromised, so Arena revokes every active refresh token of that player and answers 401 REFRESH_TOKEN_REUSED. The real user logs in again; the attacker is locked out.

arena/.../auth/AuthService.java
@Transactional
public TokenResponse refresh(RefreshRequest request) {
    String hash = tokenService.hashRefreshToken(request.refreshToken());
    RefreshToken existing = refreshTokenRepository.findByTokenHash(hash)
            .orElseThrow(() -> new ApiException(ErrorCode.INVALID_REFRESH_TOKEN, "Invalid refresh token"));

    Instant now = Instant.now(clock);
    // Expiry is checked before reuse: an expired token is a plain INVALID_REFRESH_TOKEN and must
    // not trigger the mass revocation that a replayed (revoked but unexpired) token does.
    if (!existing.getExpiresAt().isAfter(now)) {
        throw new ApiException(ErrorCode.INVALID_REFRESH_TOKEN, "Refresh token expired");
    }
    if (existing.getRevokedAt() != null) {
        UUID playerId = existing.getPlayer().getId();
        requiresNewTx.executeWithoutResult(status ->
                refreshTokenRepository.revokeAllActiveForPlayer(playerId, now));   // commits on its own
        throw new ApiException(ErrorCode.REFRESH_TOKEN_REUSED, "Refresh token was already used");
    }
    // ... issue replacement, mark existing revoked + replacedBy, return the new pair
}
Why REQUIRES_NEW? (connects to module 07)

The method throws ApiException right after revoking, and an unchecked exception makes the surrounding @Transactional transaction roll back, which would undo the revocation. Running the revocation in a separate, independent transaction (PROPAGATION_REQUIRES_NEW through a TransactionTemplate) commits it on its own, so the defensive action survives the error response. This is exactly the kind of detail interviewers probe.

Why expiry is checked first

A user who comes back after 8 days with an expired token isn't under attack. If reuse were checked first, an old expired-and-revoked token could trigger mass revocation and log the user out of every device for no reason. The project notes record that this order was fixed to match the specification, and a test covers it.

How do you revoke an access token, then?

9. Secrets

10. Mapping to the OWASP Top 10

RiskWhat Arena (and the platform) does
Broken access controlDeny by default; method-level roles; business rules on ownership, status and source; the id comes from the token
Cryptographic failuresbcrypt for passwords; HS256 with a ≥ 256-bit secret and a pinned algorithm; refresh tokens stored hashed
InjectionJPA/JDBC bind parameters everywhere; the only formatted() SQL uses constant expressions, never input
Insecure designThe model can't act; layered guardrails; append-only audit log
Security misconfigurationNo stack traces; Actuator exposure documented; CSRF off for good reason
Identification and authentication failuresShort access tokens, rotation, reuse detection, a generic login error
Software and data integrityThe database trigger blocks audit tampering
Logging and monitoring failuresStructured logs; metrics on moderation actions; no secrets in logs
Server-side request forgeryThe Judge's model can never choose a URL; tools have fixed endpoints and only the flagged player

Not yet done, and you should say so: rate limiting on login and appeals (listed as next work in Arena's README), account lockout or MFA, TLS (left to a reverse proxy in a real deployment), closing the concurrent refresh race (section 8), and cleaning up old refresh tokens: nothing deletes expired or revoked rows, so refresh_tokens grows forever (module 18 shows what that means at scale).

11. Interview questions

Why bcrypt instead of SHA-256 for passwords? Basic

SHA-256 is designed to be fast, so attackers can test billions of guesses per second against leaked hashes. bcrypt is deliberately slow with a tunable cost factor, and salts each hash, which defeats precomputed tables and makes equal passwords hash differently. Arena uses BCryptPasswordEncoder with the default cost of 10.

But you store refresh tokens with SHA-256. Isn't that inconsistent? Deep

No. The threat is different. Passwords are low-entropy and human-chosen, so slowness is the only defence against guessing. A refresh token is 32 bytes from SecureRandom (256 bits), so guessing it from its hash is infeasible however fast the hash is. A fast deterministic hash also lets me find the token in one indexed lookup; with a salted slow hash I couldn't look it up at all. Hashing protects against a database leak.

What's in a JWT and is it secret? Basic

Header, payload (claims) and signature, Base64url-encoded and joined with dots. Mine carry iss, sub (player id), iat, exp, username, roles and a custom typ=access. It's signed, not encrypted: anyone can read the claims; the signature only proves integrity and origin. So never put secrets in it.

HS256 or RS256, and why did you choose HS256? Intermediate

HS256 uses one shared secret to sign and verify; RS256 signs with a private key and verifies with a public key. Arena is both issuer and verifier, so a symmetric key is simplest and fine, with a 256-bit minimum enforced at startup and the algorithm pinned in the decoder. If other services needed to verify tokens independently, I'd switch to RS256 and publish a JWKS endpoint so only Arena can sign.

Walk me through how a request with a bearer token is authenticated. Intermediate

Spring Security's BearerTokenAuthenticationFilter extracts the token. The JWT authentication provider asks my JwtDecoder to verify the HS256 signature and validate expiry (with clock skew), issuer and my typ=access rule. My JwtAuthenticationConverter maps the roles claim to ROLE_ authorities. The resulting Authentication goes into the SecurityContext for the request. Then URL rules and @PreAuthorize check authorities. Failures are written as ProblemDetail by my entry point (401) or access-denied handler (403).

Why is CSRF disabled? Isn't that insecure? Intermediate

CSRF exploits browsers automatically attaching cookies to cross-site requests. Arena authenticates with a bearer token in the Authorization header, which browsers never attach automatically, and keeps no session cookie (STATELESS). With no ambient credential there's nothing to forge. If tokens moved into cookies, I'd re-enable CSRF protection or rely on SameSite cookies.

Explain refresh-token rotation and reuse detection. Deep

Each refresh is single-use: presenting it revokes it, records which token replaced it, and returns a new pair. If an already-revoked token shows up again, someone is replaying a token, either the thief or the victim after the thief used it first. I can't tell which, so I revoke all of that player's active refresh tokens and return 401 REFRESH_TOKEN_REUSED. The revocation runs in a REQUIRES_NEW transaction so it commits even though the outer transaction rolls back when the exception is thrown. Expired tokens are rejected before the reuse check, so an old expired token never triggers mass logout. One honest caveat: the token row isn't locked, so two concurrent refreshes with the same token can both pass the "not revoked" check and both succeed. I'd close that with a conditional UPDATE ... SET revoked_at = now WHERE id = ? AND revoked_at IS NULL, treating 0 rows updated as reuse.

How would you revoke a JWT access token immediately? Deep

You can't with pure stateless verification. That's the trade-off. Options: keep access tokens short (15 minutes) and revoke the refresh token (what Arena does); keep a deny-list of jti values in Redis checked per request; store a per-user "valid after" timestamp and compare it with iat; or rotate the signing key with kid headers. Each adds back a bit of state in exchange for faster revocation.

hasRole('SERVICE') always returns 403 even with the right claim. What do you check? Curveball

The ROLE_ prefix. hasRole('SERVICE') looks for the authority ROLE_SERVICE. By default the JWT converter reads scope/scp and prefixes with SCOPE_. Arena configures it to read the roles claim and prefix ROLE_. I'd also check that @EnableMethodSecurity is present, otherwise @PreAuthorize is ignored entirely, which is the opposite failure: everything allowed.

Where do you check that a player can only edit their own profile? Intermediate

The endpoint is PATCH /players/me: the id comes from the token's sub claim via CurrentUser.id(jwt), never from the request, so there's no id to tamper with. The service then checks the account is in good standing (not banned or under appeal), returning 403 ACCOUNT_SUSPENDED. Role checks alone wouldn't stop a PLAYER editing another PLAYER; that's broken access control.

Your login returns the same error for unknown users and wrong passwords. Is there still a leak? Curveball

Timing. For an unknown username no bcrypt comparison runs, so the response is measurably faster than for a known username with a wrong password, which could allow username enumeration. The fix is to run a comparison against a dummy hash when the user isn't found, so both paths cost the same. Add rate limiting on login too, which is on Arena's next-steps list.

Why did the Judge get its own service account instead of using the moderator's? Intermediate

Least privilege and accountability. The SERVICE role can record matches and moderation actions but can't read the human moderator queue or decide appeals. The server enforces extra rules for services (JUDGE/TELEMETRY sources only, a confidence floor for bans). And every audit row records which account acted, so automated decisions are distinguishable from human ones and can be reviewed or reversed.

12. Quick quiz

1. Anyone holding a JWT can:

Signed, not encrypted. Modification breaks the signature.

2. Why does the reuse branch use REQUIRES_NEW?

An unchecked exception rolls back the outer transaction; the inner one has already committed.

3. CSRF protection is unnecessary in Arena because:

CSRF needs an ambient credential such as a cookie.

4. A presented refresh token is both expired and revoked. Arena answers:

Expiry is checked first, deliberately.

5. hasRole('MODERATOR') checks for the authority:

hasRole adds the ROLE_ prefix.

6. Which belongs in the "business rule" layer rather than @PreAuthorize?

It depends on the request body and the caller type together, so it lives in ModerationService.enforceGuardrails.

13. Cheat sheet

  • AuthN = who (401) · AuthZ = may you (403).
  • Passwords: bcrypt (salted, slow, cost 10). Random tokens: SHA-256 is fine (high entropy, needs lookup).
  • JWT = header.payload.signature; signed, not encrypted; claims iss, sub, iat, exp, username, roles, typ.
  • HS256: shared secret, same issuer and verifier (Arena), ≥ 256-bit key, algorithm pinned. RS256: many verifiers, public key (JWKS).
  • Stateless: no session; bearer header; CSRF off (no ambient credential); CORS only if a browser frontend exists.
  • Chain: BearerTokenAuthenticationFilter → JwtDecoder (signature, exp, iss, typ) → converter (roles → ROLE_) → SecurityContext → URL rules → @PreAuthorize.
  • Deny by default: anyRequest().authenticated().
  • Three authZ layers: URL, method, business rules (the id from the token, account standing, source, confidence floor).
  • Two tokens: access JWT 15 min (unrevocable) + refresh opaque 7 d (hashed, rotated, reuse revokes all in REQUIRES_NEW; expiry checked first). Known gap: two concurrent refreshes can both succeed (no row lock); fix with a conditional UPDATE ... WHERE revoked_at IS NULL. No token cleanup yet.
  • Secrets: env only, .env ignored, .dockerignore, fail fast, never logged.
  • Next steps: rate limiting, lockout or MFA, a timing-safe login, TLS, RS256 if verification spreads.
Saved in this browser.