Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·50

Security & Identity

Exercises for Volume 3, chapter 50: authentication against authorisation; Spring Security's filter chain and authentication internals; passwords; roles and authorities; method security; sessions; CSRF; CORS; OAuth 2.0, PKCE and OpenID Connect; JWTs and resource servers; authorisation-server concepts; the BFF pattern; service-to-service authentication; and security in other frameworks. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The cryptography runs on JDK 21's built-in providers (PBKDF2, HMAC-SHA256, ECDSA P-256) with no libraries. Spring Security wasn't available offline, so its configuration exercises give expected behaviour, marked as such. Every quoted output is real, and four of them catch experienced developers:

  • P1. A login that returns early for unknown users took 0 ms for nobody against 167 ms for asha, so anyone can tell which accounts exist. Hashing a dummy password for unknown users brought the two to 133 and 152 ms.
  • P3. A token signed with HS256 using the ES256 public key as the HMAC secret was accepted by a verifier that took the algorithm from the token's header: accepts: true. The public key is public, so anyone can forge tokens that way.
  • P2. The PKCE S256 challenge for RFC 7636's example verifier came out as E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, exactly the RFC's value, from one SHA-256 and base64url encoding.
  • P1. String.equals on a 64-character secret took 1.32 ns when the first character differed and 9.34 ns when only the last did. That's the timing leak MessageDigest.isEqual avoids: 44.15 against 47.62 ns, nearly flat.

The chapter's lab already covered these, and the exercises build on them rather than repeat them:

  • password hashing speed: SHA-256 at 2.2 million guesses per second per core, against PBKDF2 600,000 iterations at 7 and bcrypt cost 10 at 14;
  • the alg: none token accepted by a naive verifier;
  • CSRF with SameSite=Lax (rejected), SameSite=None (executed), and a CSRF token (rejected);
  • CORS blocking reads without headers, and a misconfigured allow-list leaking the profile.

Coverage map.

Chapter component Exercises
authentication against authorisation T1, P6
SecurityFilterChain; authentication internals T2, P5
passwords T3, P1
roles and authorities; method security T4, P6
sessions; CSRF; CORS T5, P7
OAuth 2.0; PKCE T6, P2
OpenID Connect T6, P4
JWT; resource server T7, P3, P4
authorisation-server concepts T8
the BFF pattern T8, P8
service-to-service authentication T9, P9
security in other frameworks T9

Theory

T1. Authentication, authorisation, and where each check lives

  1. Define authentication (who are you?) and authorisation (what may you do?), with TiffinBox examples: - a customer logging in; - a kitchen tablet; - an admin; - the payment provider's webhook; - the order service calling the maps service.

For each, name the credential, what proves it, and the principal the application ends up with. 2. Explain the layers of authorisation: - coarse URL rules ("/admin/** needs ROLE_ADMIN"); - method rules (@PreAuthorize); - object-level rules ("customer 42 may only read customer 42's orders").

Why is the third the one most often missing (IDOR, OWASP's top API risk: broken object-level authorisation)? 3. Where should each check live: the gateway, the security filter chain, method security, the application service, the domain, or the database (row-level security)? Why should the decision "may this kitchen accept this order?" be in the application or domain layer, not in a URL rule?

T2. Spring Security's architecture

  1. Explain the pieces: - DelegatingFilterProxy and FilterChainProxy; - one or more SecurityFilterChain beans matched by request (securityMatcher); - the ordered filters (CORS, CSRF, the bearer-token or session authentication filters, ExceptionTranslationFilter, AuthorizationFilter); - SecurityContextHolder and its ThreadLocal (ch48's reactive caveat); - AuthenticationManager, ProviderManager and AuthenticationProviders; - the Authentication object (principal, credentials, authorities).
  2. Write two filter chains for TiffinBox: /api/** as a stateless resource server with JWTs, and /admin/** with an OIDC login and sessions. How are they ordered, and what happens to requests that match neither?
  3. How does Spring Security produce 401 and 403 responses (AuthenticationEntryPoint, AccessDeniedHandler), and how do you make them TiffinBox problem details (ch48's T3: advices never see filter exceptions)? What should a 401 include (WWW-Authenticate: Bearer error="invalid_token")?

T3. Passwords

  1. The lab: salted SHA-256 at 2.2 million guesses per second per core, against PBKDF2-SHA256 (600,000 iterations) at 7, and bcrypt cost 10 at 14. Explain why slow, salted, memory-hard hashes matter after a breach, and compare bcrypt (72-byte limit), scrypt, PBKDF2 (FIPS) and Argon2id (memory-hard; OWASP's first choice). What does P1's output show about salts (66d7d99c… against 101cf794… for the same password)?
  2. Spring Security's DelegatingPasswordEncoder stores {bcrypt}$2a$10$… or {argon2}…. How does that prefix let you upgrade algorithms and costs gradually (upgradeEncoding on login)? How do you migrate users from a legacy unsalted MD5 table without forcing resets?
  3. P1's timing results: - the naive login returned in 0 ms for unknown users and 167 ms for real ones (user enumeration); - with a dummy hash, 133 against 152 ms; - String.equals leaked the mismatch position (1.32 against 9.34 ns), while MessageDigest.isEqual didn't (44.15 against 47.62 ns).

Which comparisons in TiffinBox need constant time? Also explain rate limiting, lockout trade-offs, breached-password checks (k-anonymity), and MFA.

T4. Roles, authorities and method security

  1. Explain GrantedAuthority, roles (ROLE_ prefixed authorities: hasRole("ADMIN") checks ROLE_ADMIN), OAuth scopes (SCOPE_orders:read by default from a JWT's scope claim), and permissions. How do you map a JWT's custom roles claim into authorities (JwtAuthenticationConverter)? When are role hierarchies useful (ADMIN > SUPPORT > USER)?
  2. Method security (@EnableMethodSecurity): - @PreAuthorize("hasAuthority('SCOPE_orders:write')"); - @PreAuthorize("@orderAccess.canRead(authentication, #id)"); - @PostAuthorize("returnObject.customerId == authentication.name"); - @PostFilter.

Which ch46 proxy rules apply (self-invocation bypasses it, private methods aren't intercepted)? When is a plain check in the service clearer than SpEL? 3. Design authorisation for TiffinBox's roles: - customers (their own orders); - kitchen staff (their kitchen's orders, by status); - delivery partners (assigned deliveries only); - support (read any order, refund up to ₹500, with an audit trail); - admins.

Where do RBAC and ABAC meet, and when do you need a policy engine (OPA, Cedar, OpenFGA's relationship-based model)?

T5. Sessions, CSRF and CORS

  1. Sessions: JSESSIONID cookies, session fixation (Spring Security changes the session id on login), timeouts, concurrent session control, and Spring Session with Redis for multi-instance apps. Which cookie attributes are mandatory (HttpOnly, Secure, SameSite, Path, the __Host- prefix)?
  2. The lab's CSRF results: SameSite=Lax blocked the attacker's POST (no cookie sent), SameSite=None executed it, and a CSRF token blocked it again. Explain: - why CSRF exists (browsers attach cookies automatically); - why Lax isn't complete protection (GET with side effects, the 2-minute Lax-by-default window in some browsers, same-site subdomains); - Spring Security's CSRF token handling (CookieCsrfTokenRepository for SPAs, XorCsrfTokenRequestAttributeHandler, the SPA configuration helper); - why APIs with only bearer tokens in headers don't need CSRF protection.
  3. The lab's CORS results: no CORS headers blocked the attacker's read (the request was still sent, with cookies), and a misconfigured allow-list let the attacker read {"user": "asha", "phone": …}. Explain what CORS is (a browser's permission for reading responses across origins, not a server-side access control), preflights, the danger of reflecting Origin with Allow-Credentials: true, and TiffinBox's CORS configuration.

T6. OAuth 2.0, PKCE and OpenID Connect

  1. Explain OAuth 2.0's roles (resource owner, client, authorisation server, resource server) and the authorisation code flow, step by step:
  2. redirect with client_id, redirect_uri, scope, state and code_challenge;
  3. user login and consent;
  4. redirect back with a code;
  5. a back-channel token exchange with the code_verifier;
  6. access and refresh tokens.

Why were the implicit flow and the password grant removed in OAuth 2.1? 2. PKCE. P2 computed the RFC 7636 example: code_challenge = BASE64URL(SHA256(verifier)) gave E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM. What attack does PKCE stop (authorisation-code interception), and why is it required for all clients now, including confidential ones? What do state and nonce protect against? 3. OpenID Connect adds authentication on top of OAuth: the openid scope, the ID token (a JWT about the user: sub, iss, aud, nonce, auth_time, acr), the UserInfo endpoint, discovery (/.well-known/openid-configuration) and JWKS. Why must an API never accept an ID token as an access token, and why must the client validate the ID token's aud and nonce?

T7. JWTs and resource servers

  1. Explain a JWT's structure (header, payload, signature, base64url-encoded) and the registered claims (iss, sub, aud, exp, nbf, iat, jti). P3: an ES256 token was 266 characters with a 64-byte signature; verifying the original gave true, and changing the scope to "orders:read admin" gave false. Why is the payload readable by anyone, and what must never go in it?
  2. Algorithm attacks: - the lab's alg: none; - P3's HS256 with the public key as the HMAC secret, accepted by a naive verifier (accepts: true).

Explain why both work against verifiers that trust the header, and how Spring Security's NimbusJwtDecoder prevents them (algorithms pinned per JWK, kid lookup in the JWKS, key type checks). 3. Configure a resource server: issuer-uri (discovery and JWKS), audience validation (Spring requires an explicit JwtValidators or audiences property), clock skew (P3: with 60 s allowed, a token expiring at now + 300 was accepted at +330 and rejected at +400), key rotation and caching, and when to use opaque tokens with introspection instead. How do you revoke a JWT before it expires?

T8. Authorisation servers, and the BFF pattern for browser apps

  1. Authorisation-server concepts: - clients (public and confidential, redirect URIs); - scopes and consent; - token lifetimes; - refresh-token rotation with reuse detection; - the JWKS and key rotation; - federation (social logins, SAML or OIDC from enterprises); - why you should run Keycloak, Auth0, Cognito, Entra ID or Spring Authorization Server instead of writing one.
  2. Where should a browser SPA keep tokens? Compare: - localStorage (XSS steals tokens); - memory only (lost on reload; still exposed to XSS during the session); - the BFF pattern (a backend-for-frontend handles OAuth as a confidential client, keeps tokens server-side, and gives the browser an HttpOnly, SameSite session cookie; the BFF proxies API calls, adding the access token).

What does the BFF reintroduce (CSRF, T5) and how is it handled? 3. Mobile apps (TiffinBox's Android app): the system browser with PKCE (AppAuth), claimed HTTPS redirect links, refresh tokens in the Keystore, and no embedded web views for login. Why not embedded web views?

T9. Service-to-service authentication and other frameworks

  1. Options for the order service calling the payment, maps and notification services: - client credentials tokens with aud per target; - token exchange (RFC 8693) to act on behalf of a user with reduced scopes; - mTLS with workload identities (SPIFFE/SPIRE, service-mesh certificates); - cloud IAM (GCP service accounts, AWS IAM roles); - shared API keys (and why they rot).

What should the receiving service check? 2. Webhooks from the payment provider: HMAC over the raw body with a timestamp (ch45), constant-time comparison (P1), replay windows, and idempotency. Why must the signature be verified over the raw bytes, before JSON parsing? 3. Compare security in other frameworks: - ASP.NET Core (authentication schemes, policy-based authorisation with IAuthorizationHandler); - Django (sessions, CSRF on by default, django-allauth); - FastAPI (dependencies such as OAuth2PasswordBearer, Security scopes); - Express or NestJS (Passport strategies, guards); - Go (middleware; golang-jwt with WithValidMethods).

Which of this chapter's pitfalls (algorithm confusion, CSRF with cookies, IDOR) do their defaults prevent, and which do they leave to you?

Programming exercises

P1. Password storage and timing-safe login

With the JDK only: 1. hash passwords with PBKDF2-HMAC-SHA256 (600,000 iterations, a 16-byte salt) in a self-describing format; 2. time a naive login for a known and an unknown user, then fix the enumeration with a dummy hash; 3. compare String.equals with MessageDigest.isEqual on a 64-character secret mismatching at the first or the last character; 4. add a {pbkdf2} prefix and an upgrade path from a legacy unsalted MD5 table (T3).

P2. The authorisation code flow with PKCE, by hand

Implement the client side of the code flow against a stub authorisation server (a few lines of HttpServer, or a described flow): 1. generate the code_verifier (43–128 characters from the unreserved set) and the S256 challenge, checked against RFC 7636's example; 2. build the authorisation URL with state; 3. handle the callback (check state); 4. exchange the code with the verifier; 5. reject an exchange with a wrong verifier; 6. reject a replayed code.

P3. JWT signing, verification and algorithm confusion

With the JDK: 1. sign an ES256 JWT and verify it; 2. tamper with a claim and show verification failing; 3. forge an HS256 token using the public key bytes as the HMAC secret, and show a naive verifier (algorithm from the header) accepting it; 4. write a strict verifier that pins the algorithm per kid, validates iss, aud, exp (with 60 s skew) and nbf, and rejects none.

P4. A resource server with Spring Security

Configure the order API as a resource server (expected behaviour if Spring Security isn't available): - issuer-uri, audiences and jws-algorithms; - scope and role mapping (T4); - 401 and 403 as TiffinBox problems with WWW-Authenticate; - object-level checks for orders (T1).

Write tests with jwt() request post-processors for: - no token; - an expired token; - the wrong audience; - the wrong scope; - another customer's order; - the happy path.

P5. Two filter chains and a deny-by-default fallback

Configure T2's three chains: - the /api/** resource server; - /admin/** with OIDC login, sessions and CSRF; - everything else denied except health.

Print the filter list of each chain at startup (FilterChainProxy.getFilterChains()), and write tests proving: - an API request with a session cookie but no bearer token is rejected; - an admin POST without a CSRF token is rejected; - /random is 403; - health is public.

P6. Object-level authorisation and IDOR tests

Implement OrderAccess for T4's roles: - customers; - kitchen staff by kitchen and status; - delivery partners by assignment; - support with audited reads and a ₹500 refund limit; - admins.

Write a parameterised test matrix (role × action × ownership → allowed or not), including the IDOR cases. Then add a @PreAuthorize bean check for one endpoint, and show self-invocation bypassing it (expected, ch46).

P7. CSRF and CORS, measured

Rebuild the lab's attacker page (two origins on localhost) against a Spring app: - session cookies with SameSite=Lax against None; - Spring Security's CSRF token on and off; - a strict CORS allow-list against a reflected-origin misconfiguration.

Record what the server saw and what the page could read, then write the TiffinBox configuration (T5) and its tests. Without Spring Security, use the lab's Python servers and reason about Spring's behaviour.

P8. A BFF for the TiffinBox web app

Design and, where possible, build the BFF: - oauth2Login as a confidential client with PKCE; - server-side token storage (a session in Redis); - a __Host- session cookie with SameSite=Strict; - /api/** proxied with the access token added (TokenRelay in Spring Cloud Gateway, or RestClient with OAuth2AuthorizedClientManager); - transparent refresh; - CSRF protection for the proxied writes; - logout that revokes the refresh token and ends the identity provider's session (RP-initiated logout).

P9. Service-to-service: client credentials, audiences and webhooks

  1. Implement the order service's call to payments with client credentials (expected with Spring's OAuth2AuthorizedClientManager), caching the token until shortly before expiry.
  2. Make the payments resource server require aud = payments-api and the scope payments:create, and test a maps token (wrong audience) being rejected.
  3. Implement webhook verification over raw bytes: HMAC-SHA256 with a timestamp, a ±5-minute window, constant-time comparison, deduplication by event id, and two active secrets during rotation.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–50)

C1. Secure the order platform end to end

Apply this chapter to the order platform built in ch44–49: - the identity provider (Keycloak in a container, or a described setup) with clients for the web BFF, the Android app, the kitchen tablets and services; - the BFF for the web (P8); - resource servers with issuer, audience and algorithm pinning (P4); - authority mapping; - OrderAccess with audited support reads (P6); - problem-detail 401 and 403 responses; - CORS and CSRF per chain (P5, P7); - client credentials between services (P9); - signed webhooks (P9); - Argon2id or PBKDF2 for any local credentials (P1); - security headers; - a security test suite.

Combines: ch44's skeleton, ch45's API design and webhooks, ch46–47's Spring and Boot, ch48's web layer and problems, ch49's scoped queries, and this chapter.

C2. Kitchen tablets: device login and long-lived sessions

Design and build authentication for kitchen tablets: - the OAuth device authorisation grant (RFC 8628) for initial enrolment by a manager; - refresh-token rotation with reuse detection; - per-device revocation from an admin screen; - the tablet's SSE order stream (ch48) authenticated with short access tokens and reconnects on expiry; - offline tolerance; - audit of every accept and reject.

Combines: Volume 2's offline and UI work, ch45's SSE and resync, ch48's SseEmitter, ch49's audit tables, and this chapter.

C3. A security review of a teammate's service

Take a service from earlier chapters (ch47's or ch48's order API) and run a structured review: - the OWASP API Security Top 10 checklist; - authentication and token validation (issuer, audience, algorithm); - object-level authorisation tests; - CSRF and CORS configuration; - secrets handling (ch47's Secret type); - logging of personal data and tokens (ch47's P3); - dependency vulnerabilities; - error messages; - rate limits (ch45); - headers.

Deliver findings with severity, evidence and fixes.

Combines: ch45's API design, ch47's operations, ch48's web layer, ch49's persistence, and this chapter.

What the chapter leaves out

Passkeys and WebAuthn

Passkeys replace passwords with public-key credentials bound to the site's origin, so they can't be phished. Spring Security 6.4+ supports WebAuthn registration and authentication (http.webAuthn(…)). For TiffinBox's customers and admins, passkeys plus a fallback are the strongest practical login.

Secrets management and key rotation

Keep signing keys, client secrets and webhook secrets in a secrets manager (Vault, cloud secret managers, KMS for keys that never leave hardware), never in repositories or images. Rotate with overlap (two active keys), and audit access. Kubernetes Secrets are base64, not encryption: enable encryption at rest, or use external secret operators.

Security headers and Content Security Policy

Content-Security-Policy (with nonces, script-src 'self') is the strongest defence against XSS for the BFF's pages. Add Strict-Transport-Security with preload, X-Content-Type-Options: nosniff, Referrer-Policy, Permissions-Policy and frame-ancestors. Spring Security sets several by default. CSP needs per-application tuning.

Threat modelling and secure development

STRIDE per data flow, abuse cases next to use cases, security requirements in stories, and dependency, SAST and DAST scanning in CI, with a vulnerability response process. OWASP ASVS gives verification levels for applications, and the OWASP API Top 10 targets APIs specifically.

Privacy and data protection

India's DPDP Act (2023) and GDPR shape what TiffinBox may collect and keep: purpose limitation, consent, retention limits, data-subject requests (access, deletion), and breach notification. Security controls protect the data. Privacy design decides whether you hold it at all: minimise personal fields in tokens, logs and analytics.

Senior exercises

S1. TiffinBox's security standard

Write the standard: - identity provider and clients per app type; - the BFF for web; - PKCE everywhere; - token lifetimes and rotation; - resource-server validation (issuer, audience, pinned algorithms); - object-level authorisation in services with IDOR tests; - password and credential storage; - constant-time secret comparison; - CSRF and CORS rules per chain; - service identity; - webhooks; - logging and redaction; - headers; - secrets; - reviews and scanning.

Tie each to an output.

S2. Review a security pull request

A PR adds: - JwtDecoder built with NimbusJwtDecoder.withSecretKey(new SecretKeySpec(publicKeyBytes, "HmacSHA256")); - @PreAuthorize("hasRole('USER')") on getOrder(id) with orderRepository.findById(id); - http.csrf().disable() on the admin chain "because the SPA breaks"; - config.addAllowedOriginPattern("*"); config.setAllowCredentials(true);; - if (request.getHeader("X-Signature").equals(computeHmac(body))); - log.info("token refreshed {}", tokenResponse).

Write the review.

S3. Respond to a leaked signing key

Scenario: the private key that signs TiffinBox's access tokens was committed to a public repository 6 hours ago. Plan the response: containment, rotation, revocation, detection of abuse, communication, and prevention. What's different if it was a webhook secret, or a refresh-token database dump?

S4. Teach "security mistakes that look like working code" with five outputs

Prepare a 20-minute session using: - the lab's hash speeds (2.2 million against 7 guesses per second); - P1's enumeration (0 against 167 ms); - P3's HS256 forgery (accepts: true); - the lab's CSRF (EXECUTED); - the lab's CORS leak (READ {"user": "asha", …}).

S5. Plan an identity and security programme

As platform and security lead, plan two quarters: - moving web apps to the BFF; - passkeys for customers and admins; - resource-server hardening across all services; - IDOR test coverage; - service identity (mTLS or client credentials); - the webhook library; - secret scanning and KMS-held keys; - security headers and CSP; - dependency and DAST scanning; - the incident runbook (S3) and drills; - training (S4).

Give milestones, risks and metrics.