Skip to lesson

Practice: how Spring Security works

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.

Every Spring Security question comes down to one walk: follow the request through the filter chain, see who it is, then find the first rule that matches. Try the walk on the questions below.

Predicting 200, 401 or 403

Walk a request in order and predict its status. The lab configuration below has no anyRequest() rule, and its real answers follow the walk exactly.

Example 1 · No anyRequest rule: the real answers (security-lab)

Runs in: the security-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
package com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;
@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll()                .requestMatchers("/error").permitAll())            .httpBasic(Customizer.withDefaults())            .csrf(csrf -> csrf.disable())            .sessionManagement(session -> session                .sessionCreationPolicy(SessionCreationPolicy.STATELESS));        return http.build();    }}
Sample output
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products
200
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" -d '{"sku":"X-1","name":"Pen","price":10}' http://localhost:8080/api/v1/products
401
$ curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass-1 -X POST -H "Content-Type: application/json" -d '{"sku":"X-1","name":"Pen","price":10}' http://localhost:8080/api/v1/products
403
$ curl -s -o /dev/null -w "%{http_code}\n" -u asha:wrong http://localhost:8080/api/v1/products
401
$ curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass-1 http://localhost:8080/api/v1/me
403

What this code does

  • GET products matches permitAll: 200. A guest POST matches no rule, so it is denied, and a guest is sent to sign in: 401.
  • The same POST from signed-in asha is also denied, but she is known: 403. /api/v1/me gives her 403 for the same reason.
  • A wrong password on the public GET is 401: BasicAuthenticationFilter rejects bad credentials before any rule is checked.

To predict a status code, walk the chain in order. First, wrong credentials: if the request sends a Basic header with a wrong password, BasicAuthenticationFilter answers 401 at once, even for a public URL. Second, CSRF: with CSRF on, a POST, PUT, PATCH or DELETE without a token is rejected (and, without a public /error, shows up as 401). Third, the rules: find the first rule that matches the method and path.

Then apply the rule. permitAll gives the controller's normal answer (200, 404 and so on). authenticated gives 401 for a guest and the normal answer for a signed-in user. A denying rule, or no matching rule at all in Spring Security 7, gives 401 to a guest and 403 to a signed-in user: a guest is asked to sign in first, a known user is refused. If no sign-in method is configured at all, there is no entry point to send 401, so even guests get 403.

Predict the output

Predict the status

Walk the chain in order: credentials, CSRF, then the first matching rule.

Round 1 of 3

What status does this request get?

.requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll()
.anyRequest().authenticated()
// GET /api/v1/products/1 with a Basic header and a wrong password

Fixing outdated configuration to the Spring Security 7 DSL

Translate an outdated configuration, then compare it with the access table to see which hole it keeps.

Example 2 · A faithful translation keeps the hole (security-lab)

Runs in: the security-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
package com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.web.SecurityFilterChain;
// The 2022 tutorial, translated line by line to Spring Security 7@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .requestMatchers("/api/v1/products/**").permitAll()                .anyRequest().authenticated())            .httpBasic(Customizer.withDefaults())            .csrf(csrf -> csrf.disable());        return http.build();    }}
Sample output
Before (the 2022 tutorial, on Spring Security 7):
[ERROR] .../security/SecurityConfig.java:[14,13] cannot find symbol
  symbol:   method authorizeRequests()
  location: variable http of type org.springframework.security.config.annotation.web.builders.HttpSecurity

After the line-by-line translation (compiles and starts):
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/1
200
$ curl -i -H "Content-Type: application/json" -d '{"sku":"HACK-1","name":"Free iPhone","price":1.00}' http://localhost:8080/api/v1/products
HTTP/1.1 201
...
Content-Type: application/json

{"id":10,"sku":"HACK-1","name":"Free iPhone","price":1.00}
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/me
401

What this code does

  • The old chained code does not compile on Spring Security 7; the translation does, rule for rule.
  • requestMatchers("/api/v1/products/**").permitAll() has no method, so a guest's POST creates a product: 201.
  • The fix is a review, not a translation: requestMatchers(HttpMethod.GET, "/api/v1/products/**").

Translating an old configuration has two steps, and the second one is the one people skip. Step one is mechanical: a @Bean SecurityFilterChain instead of WebSecurityConfigurerAdapter, authorizeHttpRequests instead of authorizeRequests, requestMatchers instead of antMatchers, one lambda per part instead of .and(), and httpBasic(Customizer.withDefaults()) instead of httpBasic(). Step two is a review: the old code may have had holes, and a faithful translation keeps them. The 2022 tutorial permits /api/v1/products/** with no HTTP method, so translated line by line it compiles, starts, and lets a guest create a "Free iPhone" product with 201.

So after translating, compare every rule with your access table. For ShopLite that means requestMatchers(HttpMethod.GET, ...) for the catalogue, /error and health opened on purpose, and stateless sessions next to the disabled CSRF.

Ordering request rules and finding dead rules

A small Java checker finds dead rules in a list of rules.

Example 3 · Finding dead rules in plain Java

RuleAuditDemo.javaJava
import java.util.List;
/** A rule: method ("*" = any) and a path pattern that is exact or ends in "/**". */record Rule(String method, String pattern, String access) {
    String base() {        return pattern.endsWith("/**") ? pattern.substring(0, pattern.length() - 3) : pattern;    }
    /** True when this rule matches every request that the other rule matches. */    boolean covers(Rule other) {        boolean methodOk = method.equals("*") || method.equals(other.method());        if (!methodOk) {            return false;        }        if (pattern.equals("/**")) {            return true;        }        if (pattern.endsWith("/**")) {            return other.base().equals(base()) || other.base().startsWith(base() + "/");        }        return !other.pattern().endsWith("/**") && other.pattern().equals(pattern);    }
    @Override    public String toString() {        return method + " " + pattern + " " + access;    }}
public class RuleAuditDemo {
    /** Reports every rule that can never decide anything, because an earlier rule covers it. */    static void audit(String name, List<Rule> rules) {        System.out.println(name);        boolean clean = true;        for (int i = 0; i < rules.size(); i++) {            for (int j = 0; j < i; j++) {                if (rules.get(j).covers(rules.get(i))) {                    System.out.println("  dead rule " + (i + 1) + " (" + rules.get(i) + ") is hidden by rule "                            + (j + 1) + " (" + rules.get(j) + ")");                    clean = false;                    break;                }            }        }        if (clean) {            System.out.println("  every rule can match something");        }    }
    public static void main(String[] args) {        audit("ShopLite rules:", List.of(                new Rule("GET", "/api/v1/products/**", "permitAll"),                new Rule("GET", "/api/v1/categories/**", "permitAll"),                new Rule("*", "/actuator/health/**", "permitAll"),                new Rule("*", "/error", "permitAll"),                new Rule("*", "/**", "authenticated")));        audit("A teammate's rules:", List.of(                new Rule("*", "/api/v1/**", "authenticated"),                new Rule("GET", "/api/v1/products/**", "permitAll"),                new Rule("*", "/actuator/**", "authenticated"),                new Rule("*", "/actuator/health/**", "permitAll"),                new Rule("*", "/**", "authenticated")));    }}
Output
ShopLite rules:
  every rule can match something
A teammate's rules:
  dead rule 2 (GET /api/v1/products/** permitAll) is hidden by rule 1 (* /api/v1/** authenticated)
  dead rule 4 (* /actuator/health/** permitAll) is hidden by rule 3 (* /actuator/** authenticated)

What this code does

  • covers says whether one rule matches everything another rule matches; audit checks each rule against all rules above it.
  • ShopLite's order is clean. The teammate's list has two dead rules: the broad /api/v1/** and /actuator/** rules come first.
  • In Spring this mistake starts without any error, which is why tests guard the order.

A dead rule is a rule that can never decide anything, because an earlier rule matches every request it would match. Spring does not warn about it (only rules after anyRequest() fail at startup), and the result is usually an endpoint that is private when it should be public, or the other way round.

The ordering rule of thumb: exact paths and single methods first, then whole subtrees (/api/v1/products/**), then broad prefixes (/api/v1/**), then anyRequest(). Real projects get the same safety from tests: one test per public endpoint and one per protected area, so a reordering that hides a rule fails the build.

Find the bug

Find the dead rule

Click the line that stops another rule from ever deciding.

Guests cannot read the catalogue, although line 2 permits it.

Round 1 of 2

Interview drill: the filter chain and the SecurityContext

Say each walk out loud in one minute, with one ShopLite example each.

Text
request → DelegatingFilterProxy → FilterChainProxy → [context, CORS, CSRF, Basic, anonymous,          ExceptionTranslation, Authorization] → DispatcherServlet → controllerBasic → AuthenticationManager → Authentication → SecurityContextHolder (thread-local) → controller

The filter chain in one minute: Tomcat calls DelegatingFilterProxy, which hands the request to FilterChainProxy. That picks the first matching SecurityFilterChain and runs its filters in a fixed order: context setup, CORS, CSRF, the authentication filters, anonymous, ExceptionTranslationFilter, then AuthorizationFilter. Any filter can answer by itself; otherwise the request reaches the DispatcherServlet and your controller. Example: a guest POST /api/v1/products (401).

The SecurityContext in one minute: an authentication filter checks the credentials through the AuthenticationManager and stores the resulting Authentication (principal, erased credentials, authorities) in the SecurityContext. SecurityContextHolder keeps it in a thread-local for this request; controllers read it with @AuthenticationPrincipal or an Authentication parameter, and the filter clears it at the end. Example: GET /api/v1/me/context as asha.

Finish up

Mark complete & continue

Next: Mini project: add Spring Security to ShopLite