Skip to lesson

Practice: Spring Security review

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.

A customer reports that she can read another customer's order, and an admin URL answers a guest. Each of these bugs is one check missing, in the wrong order, or answering with the wrong status.

The whole section in one decision

Every ShopLite request faces the same checks in the same order, and the status code tells which check refused it. Example 1 models that order.

Example 1 · Which check failed? 401, 403 or 404

StatusDecisionDemo.javaJava
public class StatusDecisionDemo {    static int statusFor(boolean hasToken, boolean tokenValid, boolean roleAllowed, boolean ownsOrder) {        if (!hasToken || !tokenValid) {            return 401;              // authentication failed: who are you?        }        if (!roleAllowed) {            return 403;              // known user, but the URL rule refuses the role        }        if (!ownsOrder) {            return 404;              // owner check: a stranger must not learn the order exists        }        return 200;    }
    public static void main(String[] args) {        System.out.println("No token:              " + statusFor(false, false, false, false));        System.out.println("Expired token:         " + statusFor(true, false, true, true));        System.out.println("Asha, her order 1:     " + statusFor(true, true, true, true));        System.out.println("Asha, Ravi's order 14: " + statusFor(true, true, true, false));        System.out.println("Asha, ship order 15:   " + statusFor(true, true, false, true));    }}
Output
No token:              401
Expired token:         401
Asha, her order 1:     200
Asha, Ravi's order 14: 404
Asha, ship order 15:   403

What this code does

  • The checks run in a fixed order, so a guest asking for Ravi's order gets 401, not 404: who you are is decided first.
  • Asha reading order 14 passes the token and the URL rule; only the owner check stops her, with 404.
  • Shipping is admin-only in the URL rules, so a customer gets 403 before the service is ever called.

Authentication answers "who are you?"; authorisation answers "may you do this?". In ShopLite the first is the JWT check in the resource server, and the second has two layers: URL rules (with @PreAuthorize as a second line in the services) and owner checks in the services. The status code tells which check failed:

  • 401 unauthorized: missing, edited or expired token (or a failed login).
  • 403 forbidden: signed in, but the role is wrong for this URL or method.
  • 404 not-found: the order is missing or belongs to someone else (same answer for both).
  • 429 too-many-requests: login locked for a while, with Retry-After.

Around these checks sit the other defences of the section: BCrypt for stored passwords, refresh token rotation, CORS for browser pages on other origins, and consistent Problem Details for every error.

Predict the output

Which status does ShopLite answer?

Every token is valid unless the round says otherwise. Pick the status.

Round 1 of 4

A guest asks for Ravi's order.

GET /api/v1/orders/14
(no Authorization header)

Trace a request from token to owner check

A request trace follows one request through every layer and notes where it could stop. Examples 2 and 3 trace GET /api/v1/orders/14 with Asha's token.

One ShopLite request meets four checks in order. The CORS filter refuses an origin that is not allowed with 403. The token filter refuses a missing, edited or expired token with 401. The URL rule refuses a role that is not allowed with 403.

Example 2 · A request trace through a model of ShopLite's chain

RequestTraceDemo.javaJava
import java.util.List;import java.util.Map;
record Request(String method, String path, String token) {}
record Caller(int userId, Integer customerId, List<String> roles) {}
public class RequestTraceDemo {    static final Map<String, Caller> VALID_TOKENS = Map.of(            "asha-token", new Caller(2, 1, List.of("CUSTOMER")),            "admin-token", new Caller(1, null, List.of("ADMIN")));
    static final Map<Integer, Integer> ORDER_OWNER = Map.of(1, 1, 14, 2);
    static String handle(Request request) {        StringBuilder trace = new StringBuilder(request.method() + " " + request.path() + "\n");        // 1. BearerTokenAuthenticationFilter + JwtDecoder: signature, exp, iss        Caller caller = VALID_TOKENS.get(request.token());        if (caller == null) {            return trace.append("  token filter: no valid token -> 401 unauthorized").toString();        }        trace.append("  token filter: sub=").append(caller.userId()).append(" roles=").append(caller.roles())                .append("\n");        // 2. AuthorizationFilter: the URL rule for GET /api/v1/orders/* is CUSTOMER or ADMIN        boolean allowed = caller.roles().contains("CUSTOMER") || caller.roles().contains("ADMIN");        if (!allowed) {            return trace.append("  URL rule: role refused -> 403 forbidden").toString();        }        trace.append("  URL rule: hasAnyRole(CUSTOMER, ADMIN) ok\n");        // 3. Controller -> OrderService.get(id, CurrentUser): the owner check        int orderId = Integer.parseInt(request.path().substring(request.path().lastIndexOf('/') + 1));        Integer owner = ORDER_OWNER.get(orderId);        boolean admin = caller.roles().contains("ADMIN");        if (owner == null || !(admin || owner.equals(caller.customerId()))) {            return trace.append("  owner check: not visible -> 404 not-found").toString();        }        return trace.append("  owner check: ok -> 200").toString();    }
    public static void main(String[] args) {        System.out.println(handle(new Request("GET", "/api/v1/orders/1", "asha-token")));        System.out.println(handle(new Request("GET", "/api/v1/orders/14", "asha-token")));        System.out.println(handle(new Request("GET", "/api/v1/orders/14", "edited-token")));        System.out.println(handle(new Request("GET", "/api/v1/orders/14", "admin-token")));    }}
Output
GET /api/v1/orders/1
  token filter: sub=2 roles=[CUSTOMER]
  URL rule: hasAnyRole(CUSTOMER, ADMIN) ok
  owner check: ok -> 200
GET /api/v1/orders/14
  token filter: sub=2 roles=[CUSTOMER]
  URL rule: hasAnyRole(CUSTOMER, ADMIN) ok
  owner check: not visible -> 404 not-found
GET /api/v1/orders/14
  token filter: no valid token -> 401 unauthorized
GET /api/v1/orders/14
  token filter: sub=1 roles=[ADMIN]
  URL rule: hasAnyRole(CUSTOMER, ADMIN) ok
  owner check: ok -> 200

What this code does

  • The model keeps ShopLite's order: token filter, URL rule, then the owner check in the service.
  • The edited token never reaches the URL rule or the database: the request ends at the first filter.
  • The admin passes the owner check because canSee returns true for admins; this is a simplified model, not Spring's real classes.

Example 3 · The same traces against the real ShopLite API

Runs in: the shoplite-api Spring Boot project

Terminal
# $ASHA = Asha's access token (customer 1), $ADMIN = the admin's$ curl http://localhost:8080/api/v1/orders/14 -H "Authorization: Bearer $ASHA"$ curl -i -X PATCH http://localhost:8080/api/v1/products/6 -H "Authorization: Bearer $ASHA" \    -H "Content-Type: application/json" -d '{"price":1199.00}'$ curl http://localhost:8080/api/v1/me -H "Authorization: Bearer ${ASHA}x"     # one letter added(server log, shoplite.security)
Sample output
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 14 was not found.","instance":"/api/v1/orders/14"}
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/products/6"}
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The access token is invalid or has expired. Sign in again.","instance":"/api/v1/me"}

... WARN  ... shoplite.security : ACCESS_DENIED PATCH /api/v1/products/6 user=2 ip=0:0:0:0:0:0:0:1
... INFO  ... shoplite.security : NO_VALID_TOKEN GET /api/v1/me ip=0:0:0:0:0:0:0:1

What this code does

  • Order 14 answers 404 with the same body a missing order gets, so Asha learns nothing about Ravi's orders.
  • The 403 keeps Spring's insufficient_scope header and is logged as ACCESS_DENIED with the user id, never an e-mail.
  • One changed letter breaks the signature: 401 from the resource server, logged as NO_VALID_TOKEN.

The layers, in the order the request meets them:

  • CorsFilter: only for browser requests with an Origin header; preflights stop here.
  • BearerTokenAuthenticationFilter: reads the header; the JwtDecoder checks the HS256 signature, exp (with 30 s clock skew) and iss. A failure ends in 401.
  • The roles converter turns "roles":["CUSTOMER"] into ROLE_CUSTOMER, and the SecurityContext holds the Jwt.
  • AuthorizationFilter: the first matching URL rule, GET /api/v1/orders/* for CUSTOMER or ADMIN, passes. A failure ends in 403.
  • OrderController builds CurrentUser from the token, and OrderService.get loads order 14 and calls visibleTo: customer 2's order is not Asha's, so 404.

Only the last step knows about data. That is why owner checks live in the service, not in URL rules: the URL /api/v1/orders/14 looks the same for every customer.

Order of execution

Order the checks

Tap the checks in the order a browser request meets them.

Fix a broken configuration end to end

A broken security configuration usually compiles and still answers 200 on the happy path. The snippet below has six classic mistakes; review it in the order a request travels.

Java
http    .authorizeHttpRequests(auth -> auth        .requestMatchers("/api/v1/products/**").permitAll()          // 1        .anyRequest().authenticated()                                // 2        .requestMatchers("/api/v1/customers/**").hasRole("ADMIN"))  // 3    .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))   // 4    .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));  // 5// CorsConfig: api.setAllowedOrigins(List.of("*")); api.setAllowCredentials(true);    // 6

Example 4 · First match wins: the broken rules and the fixed rules

RuleOrderDemo.javaJava
import java.util.List;
record Rule(String method, String pattern, String access) {
    boolean matches(String requestMethod, String path) {        boolean methodOk = method.equals("*") || method.equals(requestMethod);        boolean pathOk = pattern.endsWith("/**")                ? path.startsWith(pattern.substring(0, pattern.length() - 3))                : path.equals(pattern);        return methodOk && pathOk;    }}
public class RuleOrderDemo {    // First matching rule wins, exactly like authorizeHttpRequests    static String decide(List<Rule> rules, String method, String path) {        for (Rule rule : rules) {            if (rule.matches(method, path)) {                return rule.access();            }        }        return "no rule matched: denied";    }
    public static void main(String[] args) {        List<Rule> broken = List.of(                new Rule("*", "/api/v1/products/**", "permitAll"),        // meant for GET only                new Rule("*", "/api/**", "authenticated"),                new Rule("*", "/api/v1/customers/**", "ADMIN"));         // never reached        List<Rule> fixed = List.of(                new Rule("GET", "/api/v1/products/**", "permitAll"),                new Rule("*", "/api/v1/products/**", "ADMIN"),                new Rule("*", "/api/v1/customers/**", "ADMIN"),                new Rule("*", "/**", "denyAll"));
        String[][] requests = { { "GET", "/api/v1/products/6" }, { "PATCH", "/api/v1/products/6" },                { "GET", "/api/v1/customers/2" }, { "GET", "/api/v1/reports" } };        for (String[] r : requests) {            System.out.printf("%-5s %-20s broken: %-13s fixed: %s%n", r[0], r[1],                    decide(broken, r[0], r[1]), decide(fixed, r[0], r[1]));        }    }}
Output
GET   /api/v1/products/6   broken: permitAll     fixed: permitAll
PATCH /api/v1/products/6   broken: permitAll     fixed: ADMIN
GET   /api/v1/customers/2  broken: authenticated fixed: ADMIN
GET   /api/v1/reports      broken: authenticated fixed: denyAll

What this code does

  • With the broken list, PATCH /api/v1/products/6 is permitted: rule 1 did not say GET.
  • The customers rule comes after /api/**, so it never matches; GET /api/v1/customers/2 is open to every signed-in user.
  • The fixed list ends with a deny-all rule, so /api/v1/reports, an endpoint nobody listed, is refused.

Example 5 · CORS checks the origin exactly

OriginCheckDemo.javaJava
import java.util.List;
public class OriginCheckDemo {    static final List<String> ALLOWED = List.of("http://localhost:3000", "https://shoplite.example");
    static String preflight(String origin) {        return ALLOWED.contains(origin) ? "200, Access-Control-Allow-Origin: " + origin : "403 Invalid CORS request";    }
    public static void main(String[] args) {        for (String origin : List.of("http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:3000/",                "https://shoplite.example", "https://shoplite.example.evil.example")) {            System.out.println(origin + " -> " + preflight(origin));        }    }}
Output
http://localhost:3000 -> 200, Access-Control-Allow-Origin: http://localhost:3000
http://127.0.0.1:3000 -> 403 Invalid CORS request
http://localhost:3000/ -> 403 Invalid CORS request
https://shoplite.example -> 200, Access-Control-Allow-Origin: https://shoplite.example
https://shoplite.example.evil.example -> 403 Invalid CORS request

What this code does

  • 127.0.0.1:3000 is a different origin from localhost:3000, even on the same computer.
  • A trailing slash or a longer host name is not the same origin, so a look-alike site gets the same refusal.
  • The real ShopLite answers a refused preflight with 403 Invalid CORS request, as in this model.

The six mistakes, by their numbers:

  • 1 permits every method on products, so anyone can change a price.
  • 2 catches every remaining request, so rule 3 is never reached and any signed-in customer reads all customers.
  • 4 keeps the default converter, which reads the scope claim, so ShopLite's roles never become ROLE_ authorities.
  • 5 allows sessions in a stateless API.
  • 6, an allowed origin of * with credentials, is refused by Spring at the first CORS request, and would trust every website if it were not.

Fix the error

Fix the URL rules

Each rule list lets the wrong request through. Pick the replacement for the highlighted line.

Round 1 of 2

A customer must not change a price.

http.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/products/**").permitAll()
.requestMatchers("/api/v1/products/**").hasRole("ADMIN")
.anyRequest().denyAll());

Error

PATCH /api/v1/products/6 with Asha's token -> 200 (expected 403)
Rules are checked top to bottom and the first match wins. Put the most specific rules first and anyRequest().denyAll() last.

Interview drill: design security for an e-commerce API

"How would you secure an online shop's API?" is a common placement question. A strong answer follows a fixed order, so no layer is forgotten.

Example 6 · Interview drill: refresh token rotation in ten lines

RefreshRotationDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class RefreshRotationDemo {    // token -> family; a token is used up (revoked) after one refresh    static final Map<String, String> familyOf = new HashMap<>();    static final Map<String, Boolean> revoked = new HashMap<>();    static int counter = 0;
    static String issue(String family) {        String token = "rt-" + (++counter);        familyOf.put(token, family);        revoked.put(token, false);        return token;    }
    static String refresh(String token) {        if (!familyOf.containsKey(token)) {            return "401 (unknown token)";        }        String family = familyOf.get(token);        if (revoked.get(token)) {            // Reuse: the old token was stolen or the client has a bug. End the whole login.            familyOf.forEach((t, f) -> { if (f.equals(family)) revoked.put(t, true); });            return "401 (reuse: family " + family + " revoked)";        }        revoked.put(token, true);        return "200 new token " + issue(family);    }
    public static void main(String[] args) {        String first = issue("login-A");        System.out.println("login        -> " + first);        System.out.println("refresh rt-1 -> " + refresh(first));        System.out.println("refresh rt-1 -> " + refresh(first));        System.out.println("refresh rt-2 -> " + refresh("rt-2"));    }}
Output
login        -> rt-1
refresh rt-1 -> 200 new token rt-2
refresh rt-1 -> 401 (reuse: family login-A revoked)
refresh rt-2 -> 401 (reuse: family login-A revoked)

What this code does

  • Each refresh uses up the old token and issues a new one in the same family.
  • Using rt-1 a second time is the sign of a stolen token, so the whole family is revoked, including rt-2.
  • In ShopLite the tokens are random 256-bit strings stored as SHA-256 hashes; the model keeps only the logic.

For ShopLite the order is: who the users are (guest, customer, admin); how they prove it (BCrypt passwords, a short-lived signed access token plus a rotating refresh token); what each may do (URL rules with deny by default, method security for admin actions, owner checks for customer data); how errors look (401/403 Problem Details); and how you would notice an attack (failed-login limits, CORS for the web shop, secrets in the environment, security logs, tests for every rule).

Use numbers and names from your project ("15 minutes", "404 for other customers' orders", "AccessMatrixIT has 28 rows"). Numbers and names show you built it, not only read about it.

Find the bug

Find the weak security line

Each snippet is part of a security design. Tap the weak line.

CORS for the web shop.

Round 1 of 4

Finish up

Mark complete & continue

Next: Project: Secure ShopLite