Authorisation, CSRF and CORS in Depth

Authorisation, CSRF and CORS in Depth in Spring Boot: An office building runs on one electronic access panel.

The Analogy: A Building Access-Control System Checked Rule by Rule

An office building runs on one electronic access panel. Every interior door has a card reader, and the panel holds a single ordered list of rules. Each rule pairs a place with a requirement: the lobby needs no card, any floor-two door needs any staff badge, the finance room needs a badge carrying the "finance" permission, the server room needs a badge carrying "infrastructure". When a badge taps a reader, the panel walks the list from the top and stops at the very first rule whose place covers that door. That rule, and only that rule, decides whether the bolt slides back.

The badge itself carries nothing but a set of flat permission strings -- "staff", "finance", "reception" -- written onto its chip when the badge was issued. The panel does not care what job title the holder has; it compares the strings the door's rule demands against the strings the badge actually carries. A "manager" is not a special kind of person to the panel, only a badge that happens to carry a broader set of strings. Two people with identical strings are identical to the system, and a badge missing the string a door asks for is turned away with a red light no matter who holds it.

Ordering is the whole game. Because the panel stops at the first covering rule, a specific rule only fires if it sits above the broader rule that would otherwise swallow it. "Server room -- infrastructure only" has to appear before "any floor-two door -- any staff", or the general rule matches the server room first and the specific one becomes dead ink. The person programming the panel is really deciding precedence, not just listing places, and the list is read top-down exactly the way the panel evaluates it.

The failure mode is one line in the wrong order. An administrator, meaning to be helpful, adds "all doors -- any staff" near the top so people stop calling about locked rooms. From that moment the panel matches that broad rule first at every interior door, the server room included, and every specific rule below it is never reached. Nothing looks wrong: badges tap, lights turn green, the building runs. Months later an audit finds that any member of staff could have walked into the server room the whole time. The lock worked perfectly; the order of the rules did not.

Syntax or Core Structure

Spring Security stores a set of authorities (plain strings) on the authenticated principal. A "role" is just an authority prefixed by convention with ROLE_. Authorisation rules form an ordered list of matcher and requirement pairs, and the first matching rule wins -- exactly like the access panel.

http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/public").permitAll()
    .requestMatchers("/admin/**").hasRole("ADMIN")       // needs ROLE_ADMIN
    .requestMatchers("/reports/**").hasRole("USER")      // needs ROLE_USER
    .anyRequest().authenticated());

Take a user whose only authority is ROLE_USER and who is authenticated. Each request is matched top-to-bottom; the first rule that covers the path decides, and its requirement is checked against the user's authorities.

Output:

request        matched rule   requires         granted
------------------------------------------------------
/public        /public        permitAll        yes
/reports/q3    /reports/**    ROLE_USER        yes
/admin/users   /admin/**      ROLE_ADMIN       no
/account       /**            authenticated    yes
------------------------------------------------------
user authorities  : ROLE_USER
granted           : 3
denied (403)      : 1

permitAll needs no authority; /reports/q3 matches the ROLE_USER rule the user satisfies; /admin/users demands ROLE_ADMIN, which the user lacks, so the panel shows red -- an HTTP 403. /account falls through to anyRequest().authenticated(), and the user is authenticated, so it passes. One badge, four doors, four independent decisions.

Technical Depth: Ordering, CSRF and the Rules That Bite

First match wins, so broad rules go last

The most dangerous authorisation mistake is placing a broad matcher above a specific one. Because evaluation stops at the first match, the specific rule below never runs, and nothing warns you.

// BUGGY: broad rule first, the specific rule below is dead
.requestMatchers("/api/**").authenticated()
.requestMatchers("/api/admin/**").hasRole("ADMIN")

// FIXED: specific rule first
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").authenticated()

A logged-in, non-admin user (authority ROLE_USER) requests /api/admin/delete:

Output:

config  request            matched         decision
----------------------------------------------------
buggy   /api/admin/delete  /api/**         GRANT
fixed   /api/admin/delete  /api/admin/**   DENY
----------------------------------------------------
user is admin        : no
buggy admin reachable: yes
fixed admin reachable: no
safe ordering        : fixed

In the buggy ordering the request matches /api/** first, whose requirement is only authenticated, so a non-admin reaches the admin endpoint. The fixed ordering puts the specific rule first and the same request is denied. Both configurations start cleanly; the order is the only difference between an open door and a locked one.

CSRF guards the state-changing methods

Cross-site request forgery works because the browser attaches a session cookie to a cross-site request automatically. Spring's CsrfFilter exempts the safe HTTP methods (GET, HEAD, OPTIONS, TRACE), which by contract must not change state, and requires a valid token on every unsafe method.

MethodChanges stateCSRF token required
GETnono (exempt)
HEADnono (exempt)
POSTyesyes
PUTyesyes
DELETEyesyes

A cross-site attacker can make the browser send the cookie but cannot read the token to include it, so unsafe requests without a valid token are rejected:

Output:

method  token    csrf checked  result
--------------------------------------
GET     n/a      no            allow
POST    valid    yes           allow
POST    missing  yes           block 403
PUT     invalid  yes           block 403
DELETE  valid    yes           allow
--------------------------------------
safe methods exempt : yes
blocked (403)       : 2
allowed             : 3

The two unsafe requests without a valid token are blocked with 403; the safe GET and the token-bearing POST and DELETE pass. The token is what separates a genuine same-site form post from a forged cross-site one.

Real World Example: A CORS Rule That Trusts Everyone

The team wants a browser front-end on app.example.com to call the API with credentials (a session cookie). The correct configuration names that origin explicitly and enables credentials only for it:

@Bean
CorsConfigurationSource corsSource(SecurityProperties props) {
    CorsConfiguration cfg = new CorsConfiguration();
    cfg.setAllowedOrigins(props.getAllowedOrigins());    // explicit allowlist from config
    cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    cfg.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    cfg.setAllowCredentials(true);                        // cookies allowed cross-origin
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", cfg);
    return source;
}

Under deadline pressure a developer hits a CORS error from a staging host and applies the first fix a search suggests: reflect whatever origin arrives. setAllowedOrigins(List.of("*")) is rejected by the browser when credentials are on, so the "fix" becomes setAllowedOriginPatterns(List.of("*")), which reflects the caller's own Origin back in Access-Control-Allow-Origin and keeps allowCredentials true. Compare the two configs against three incoming origins:

Output:

config       origin                      ACAO reflected  credentials
--------------------------------------------------------------------
allowlist    https://app.example.com     yes             yes
allowlist    https://evil.example        no              no
allowlist    https://partner.test        no              no
reflect-any  https://app.example.com     yes             yes
reflect-any  https://evil.example        yes             yes
reflect-any  https://partner.test        yes             yes
--------------------------------------------------------------------
allowlist credentialed origins  : 1
reflect-any credentialed origins: 3
safe config                     : allowlist

The allowlist grants a credentialed cross-origin response to exactly one origin: the one it was told to trust. The reflect-any config grants it to all three, including evil.example. Because credentials are on, a logged-in victim who visits the attacker's page has their cookie attached to a cross-origin request, and the browser then lets the attacker's JavaScript read the response. This is account takeover by configuration, not by any flaw in the authentication code.

The design flaw is in the code shown: pairing allowedOriginPatterns("*") with allowCredentials(true) turns the origin check into a rubber stamp. The wildcard pattern gets reached for because it silences the error in every environment at once, but "reflect any origin" is the opposite of an allowlist. A second, quieter flaw is treating CORS as access control at all: CORS only constrains browsers, so a non-browser client such as curl or a server-side proxy ignores it entirely, and the endpoint's real protection still has to be its authentication and authorisation rules.

The honest limits of this model are worth stating. It counts which origins receive a credentialed Access-Control-Allow-Origin; it does not model preflight caching, the Vary header a reflecting server must send, or per-method allow-lists. Those matter in production, but none of them change the core result: the moment an origin check reflects arbitrary input while credentials are enabled, every site on the internet becomes a trusted origin.

Common Mistakes

  1. Putting a broad matcher above a specific one. First match wins, so requestMatchers("/api/**") above requestMatchers("/api/admin/**") makes the admin rule dead configuration, and the application still starts cleanly.
  2. Confusing hasRole with hasAuthority. hasRole("ADMIN") checks for ROLE_ADMIN while hasAuthority("ADMIN") checks for ADMIN; storing one and checking the other silently denies everything or grants nothing.
  3. Disabling CSRF while authenticating by cookie. csrf().disable() copied from a tutorial leaves a cookie-authenticated form open to forged cross-site posts, which is exactly the attack CSRF protection exists to stop.
  4. Putting method security only on the controller. Scheduled jobs, message listeners, and other services reach the service directly, so a rule only on the controller does not cover them.
  5. Skipping the object-level ownership check. A rule that lets ROLE_USER call GET /api/invoices/{id} still lets one user read another's invoice by changing the id; the URL pattern is identical for everyone.
  6. Using @PostAuthorize to guard a method with side effects. It runs after the body executes, so the work is already done by the time the return value is rejected.
  7. Writing permitAll() with a broad wildcard. permitAll() on /api/** opens far more than intended; list exact paths and add a test that an anonymous call to a protected route returns 401.
  8. Pairing allowedOriginPatterns("*") with allowCredentials(true). Reflecting any origin while sending cookies lets every site make authenticated cross-origin requests.
  9. Treating CORS as access control. CORS only constrains browsers; a non-browser client ignores it, so it never replaces authentication and authorisation.

Best Practices

  • Deny by default and put anyRequest().authenticated() last, so an unmatched path is refused rather than accidentally public.
  • Order matchers specific-first, and keep permitAll() entries as exact paths rather than broad wildcards.
  • Choose one convention for roles versus authorities, apply it in your UserDetailsService, and prefer fine-grained authorities for permissions.
  • Bind ownership into the repository query (findByIdAndOwnerId) so the safe path is also the shortest one to write.
  • Put method security on the service layer, where scheduled jobs and listeners also reach it, not only on the controller.
  • Keep CSRF enabled wherever a cookie carries the credential, and disable it only with a comment explaining why no cookie is involved.
  • Enumerate CORS origins per environment, and never combine a wildcard origin with allowCredentials(true).
  • Return 404 rather than 403 when hiding a record's existence, and add tests asserting anonymous access to a protected route is refused.

Practice Exercises

  1. Given the ordered rules permitAll on /public, hasRole("ADMIN") on /admin/**, and authenticated on /**, state the decision for a ROLE_USER request to /admin/reports and explain which rule decided it.
  2. Reorder a broken configuration where requestMatchers("/api/**").authenticated() sits above requestMatchers("/api/admin/**").hasRole("ADMIN"), and write the test that would have caught the bug.
  3. Explain why a GET request needs no CSRF token but a POST does, then describe what a valid token proves that a session cookie alone does not.
  4. Take a CORS config that uses allowedOriginPatterns("*") with allowCredentials(true) and rewrite it as a per-environment allowlist, naming the one origin that should be trusted in production.