Method security, CORS and CSRF

@PreAuthorize with SpEL, role hierarchies, CORS configured on purpose, and the CSRF decision for a stateless API.

13 min read🔐 Spring Security

URL rules protect paths. A lot of what you want to protect is not a path — it is a method, called from several places, operating on an object whose owner decides the answer. That is what method security is for, and this lesson also covers the two browser mechanisms that confuse people most.

@PreAuthorize, and where the check belongs

Turn it on, then annotate:

java
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)   // Spring Security 5
public class SecurityConfig { ... }
 
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/method/hello")
public String guarded() { return "guarded by an annotation"; }
plaintext
/method/hello as ana  (ROLE_USER)  -> HTTP 403
/method/hello as root (ROLE_ADMIN) -> HTTP 200

Same 403 as a URL rule, from a different mechanism: a proxy around the bean, which is the same machinery as @Transactional — and it has the same blind spot. A call from inside the same class does not go through the proxy, so the annotation does nothing. Private and final methods likewise.

The reason to use it is that it goes where a filter cannot:

java
@PreAuthorize("hasRole('ADMIN') or #order.customerId == authentication.principal.customerId")
public void cancel(Order order) { ... }

That expression names the argument. No URL rule can express it, because a filter does not know which order. #order is the parameter, authentication is the current Authentication, and @beanName.method(...) lets you call your own code for anything more complicated.

Three relatives worth knowing:

  • @PostAuthorize checks the return value — returnObject.ownerId == authentication.name. Useful, and remember the method already ran: any side effect has happened, and any lazy loading has happened too.
  • @PreFilter / @PostFilter remove elements from a collection. Convenient and quietly expensive: @PostFilter fetches everything and then discards, so filtering a thousand rows down to three loads a thousand. Filter in the query, as the authorisation lesson argued.
  • @Secured / @RolesAllowed are the older, simpler forms — roles only, no expressions.

CORS is the browser's rule, not your security

A browser stops JavaScript on https://app.example.com reading a response from https://api.example.com unless the API says it is allowed. That is the same-origin policy, and CORS is how you make an exception to it.

Two things follow that people get backwards:

  • CORS is enforced by the browser, so it protects your users, not your API. curl ignores all of it, which is why an API still needs authentication and authorisation exactly as before.
  • A blocked request usually was sent and did run. For simple requests the browser makes the call and then refuses to let the script read the answer. Blocking before the request is what the preflight is for.

For anything that is not simple — a custom header, a PUT, JSON with Content-Type: application/json — the browser first sends a preflight:

plaintext
OPTIONS /private/hello
Origin: https://app.example.com
Access-Control-Request-Method: GET

Configured correctly, the answer permits it:

plaintext
HTTP/1.1 200
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Credentials: true

And an origin you did not allow is refused, with no CORS headers at all:

plaintext
HTTP/1.1 403

The CORS configuration that silently does nothing

This is worth its own section because the failure is invisible. In Spring Security, http.cors() looks for a CorsConfigurationSource bean by name. Name the bean anything else and it is never used:

java
@Bean CorsConfigurationSource corsSource() { ... }            // ignored
@Bean CorsConfigurationSource corsConfigurationSource() { ... } // used

With the wrong name, the preflight above returned 403, the real request returned 200 with no Access-Control-Allow-Origin header, and nothing in any log said why. The browser then reports a generic CORS error and the search begins in the wrong place.

When CORS appears not to work, check the bean name before anything else.

Two more settings that matter:

  • allowCredentials(true) cannot be combined with allowedOrigins("*"). The specification forbids it and the browser will refuse. Name the origins.
  • allowedOriginPatterns exists for wildcards within a domain and is the escape hatch when you genuinely need https://*.example.com. Use it deliberately; * with credentials is the configuration that turns a CORS policy into no policy.

CSRF, and the decision for an API

CSRF is: a user is logged into your site; another site causes their browser to send a request to yours; the browser attaches the cookie automatically; your server sees a valid session and acts.

The whole attack depends on credentials the browser sends without being asked — cookies, and HTTP basic. That gives you the rule:

  • Session cookies → CSRF protection on. A browser form app needs it.
  • A token in an Authorization header → not needed. The browser does not attach that header on its own; the attacking page would have to read the token and add it, and if it can do that you have XSS, not CSRF.

Which is why csrf().disable() next to SessionCreationPolicy.STATELESS is coherent rather than lazy: one says no cookie carries authentication here, the other says so there is nothing for CSRF to exploit. Disabling CSRF while still using session cookies is the version that is actually dangerous.

When you do need it, Spring's default is a synchroniser token that the server issues and the client returns in a header. For a JavaScript front end the cookie-based repository is the usual arrangement:

java
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

withHttpOnlyFalse() is deliberate and often misread: the CSRF token cookie is meant to be readable by your own JavaScript, because the client's job is to copy it into a header. That is safe — an attacker's page cannot read a cookie from your domain — and it is the difference between the CSRF cookie and the session cookie, which must stay HttpOnly.

SameSite is the modern half of this. SameSite=Lax on the session cookie stops it being sent on most cross-site requests, which removes much of the attack surface at the browser. It is a good defence and not a complete one — older browsers, and GET navigations under Lax — so it complements a CSRF token rather than replacing it.

Under the hood: an AOP proxy, a double-submitted token, and what a browser actually sends before the "real" request

@PreAuthorize is not the filter chain reaching into your method — it cannot be. The chain is still on the call stack while DispatcherServlet runs (the previous lesson's nesting), but it only ever sees the request: a URL and headers, never which bean method the controller will go on to call. The check happens because Spring wraps the annotated bean in a proxy at startup: a JDK dynamic proxy if the bean implements an interface, a CGLIB subclass otherwise, registered in the application context in place of your original object. Every caller that gets the bean injected actually holds the proxy, and the proxy's method implementation is a MethodInterceptor — MethodSecurityInterceptor under the @EnableGlobalMethodSecurity shown above, AuthorizationManagerBeforeMethodInterceptor under its Spring Security 6 replacement @EnableMethodSecurity — that evaluates the SpEL expression, then either throws AccessDeniedException or delegates to the real method via reflection. This is the exact same proxy machinery @Transactional uses (the spring-core course's AOP lesson has the full mechanics), and it fails the exact same way for the exact same reason: a call from inside the class — this.cancel(order) rather than orderService.cancel(order) — never goes through the proxy at all, because this inside the real object is a reference to the real object, not to the wrapper sitting in front of it. The interceptor is never invoked, so the annotation is silently a no-op. That is a proxy-interception limit, not a filter-ordering one, which is why "annotate the controller too, just in case" does not fix it — the controller calling the service still goes through the proxy correctly; the bug only appears when the service calls itself.

CSRF's double-submit mechanic is worth tracing the same way the JWT lesson traced a signature check, because "double-submit" names the whole defence in two words once you see why it works. The server issues a random token and puts it in two places the attacker's page cannot both control: a cookie (which the browser will attach automatically, same as the session cookie) and a value the legitimate page's own JavaScript reads out of that cookie and puts in a request header. On submission the server compares the header value against the cookie value. An attacker's forged cross-site request can make the browser attach the cookie automatically — that part of CSRF still works exactly as always — but the attacker's page cannot read your domain's cookie to also set the matching header, because the browser's same-origin policy forbids a script from reading another origin's cookies (CORS, by contrast, is the mechanism for relaxing that policy for responses, and never exposes cookies). The header either is missing, or carries whatever the attacker's page could fabricate, which will not equal the cookie value it was never allowed to read. The token does not need to be secret from the legitimate page — the legitimate page is trusted to read its own domain's cookies — it only needs to be unreadable cross-origin, which the browser already guarantees.

CORS preflight is a real, separate HTTP exchange that happens before the browser will even attempt the request it actually wants to make, for any request that is not "simple" by the CORS spec's own definition (roughly: not GET/HEAD/POST-with-a-simple-content-type, or carrying a custom header). The browser sends an OPTIONS request to the same URL, carrying Origin, Access-Control-Request-Method and (if custom headers are involved) Access-Control-Request-Headers — and crucially, this OPTIONS request carries no cookies, no Authorization header, none of the application's own credentials, because it is not the application's request at all, it is the browser asking the server's permission on the script's behalf. A server has to answer that OPTIONS request with no session, no bearer token and no authenticated principal. With http.cors() wired to a CorsConfigurationSource, Spring Security's CorsFilter does exactly that: it sits early in the chain, recognises a valid preflight and writes the response itself, before any authorization rule runs. The failure the lesson's "silently does nothing" section describes is what happens when that wiring is missing — CORS handled only in Spring MVC, or the config bean not found — so the preflight falls through to the authorization rules, gets a 401 or 403 before the browser ever sends the real request, and the developer sees a generic CORS failure in the console rather than an authentication failure, because the browser never surfaces what the preflight actually got back. An explicit permitAll() for OPTIONS is the workaround for CORS configured outside the security chain, not a step the correct setup needs.

Try it yourself

Work out why the double-submit token still stops a forged request

An attacker's page on evil.example runs JavaScript that issues fetch("https://app.example.com/transfer", { method: "POST", credentials: "include" }). The victim is logged into app.example.com, so the browser happily attaches the session cookie to that request — CSRF's whole premise holds. app.example.com uses the cookie-based double-submit pattern from this lesson: a CSRF-TOKEN cookie, and a required X-CSRF-TOKEN header that must match it.

Before reading on: does the attacker's forged request succeed, and specifically — what stops it, given that the browser is willing to attach the victim's cookie automatically?

The browser attaches the cookie, but same-origin policy still blocks reading it

The forged request does carry the session cookie and the CSRF-TOKEN cookie automatically — cookies attach based on the target domain, not the page that triggered the request, which is exactly why CSRF is possible at all. But the attacker's script on evil.example cannot read document.cookie for app.example.com — that is ordinary same-origin policy, nothing CORS-specific, and no Access-Control-Allow-Origin header from app.example.com changes it, because the attacker's script never gets to make a same-origin read in the first place. Without reading the cookie's value, the attacker's script cannot compute a matching X-CSRF-TOKEN header to attach to the fetch() call. The request arrives with a valid session cookie and either a missing or wrong CSRF header, and the server rejects it on that mismatch. The defence never depended on the token being a secret from the user — it depended on the token being unreadable from a page the user did not intend to trust.

Misconceptions

  • "Adding @PreAuthorize to a public method is always enough, wherever it's called from." It is enough only when the call arrives through the Spring-managed proxy. A same-class call — including one method calling a private helper, or calling another @PreAuthorize-annotated method on this — bypasses the proxy entirely and the check simply never runs, with no error and no log line to notice by.
  • "CORS blocks the attacker's request the same way a firewall would." CORS is enforced by the browser reading the response, not by the server refusing to process the request — for a "simple" request the server may well have already run the handler and produced a result before the browser decides to withhold it from the calling script. It protects a legitimate user's browser from a malicious page reading data it should not see; it does nothing for a request made with curl, a server-to-server call, or any client that was never going to enforce same-origin policy in the first place.

Sources

  • Spring Security Reference — Method Security (@PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter, proxy-based authorization).
  • Spring Framework Reference — Aspect Oriented Programming with Spring (proxy creation, self-invocation).
  • MDN Web Docs — Cross-Origin Resource Sharing (CORS), preflight requests.
  • OWASP Cross-Site Request Forgery Prevention Cheat Sheet (double-submit cookie pattern).
Progress is saved on this device and to your account when signed in.