Cheatsheet
Authorization: URLs and methods
Key idea
Once the user is authenticated, Spring Security decides whether they may access each resource. At URL level, with rules in `authorizeHttpRequests` evaluated in order; at method level, with `@PreAuthorize`, `@PostAuthorize`, `@Secured` or `@RolesAllowed`, applied by a proxy. If access is denied, the response is 401 (not authenticated) or 403 (not allowed).
Diagram (UML)
flowchart TB
req(["Request (already authenticated or anonymous)"]) --> csrf{"State-changing method<br/>without CSRF token?"}
csrf -- yes --> f403a["403 (CsrfFilter)"]
csrf -- no --> url{"AuthorizationFilter:<br/>first matching requestMatchers rule"}
url -- "permitAll / rule satisfied" --> mvc["DispatcherServlet → controller"]
url -- "denied" --> who{"Anonymous?"}
who -- yes --> f401["401 (AuthenticationEntryPoint)"]
who -- no --> f403b["403 (AccessDeniedHandler)"]
mvc --> pre{"@PreAuthorize / @Secured / @RolesAllowed<br/>on the service proxy"}
pre -- false --> f403c["AccessDeniedException → 403"]
pre -- true --> run["method runs"]
run --> post{"@PostAuthorize<br/>(returnObject)"}
post -- false --> f403c
post -- true --> ok["200"]Key pieces
authorizeHttpRequests(auth -> auth.requestMatchers(...).hasRole(...)…anyRequest()…)permitAll(),denyAll(),authenticated(),hasRole(),hasAnyRole(),hasAuthority(),hasAnyAuthority(),access(...)@EnableMethodSecurity(prePostEnabledby default;securedEnabled,jsr250Enabled)@PreAuthorize("SpEL"),@PostAuthorize("… returnObject …"),@Secured("ROLE_X"),@RolesAllowed("X")AuthorizationFilter,ExceptionTranslationFilter,AccessDeniedException- CSRF:
CsrfFilter,csrf(...); in tests,.with(csrf())
SecurityConfig.java
@Bean
public SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth // evaluated top-down: first match wins
.requestMatchers("/api/public/**").permitAll()
.requestMatchers(HttpMethod.DELETE, "/api/wods/**").hasRole("ADMIN") // specific first…
.requestMatchers(HttpMethod.POST, "/api/wods/**").hasRole("COACH")
.requestMatchers("/api/admin/**").hasAuthority("ROLE_ADMIN") // same as hasRole("ADMIN")
.anyRequest().authenticated()) // …general last
.httpBasic(withDefaults()); // CSRF stays ON (the default)
return http.build();
}Remember for the exam
- URL rules are evaluated top-down and the first match wins: specific before general
anyRequest()goes last; no rule can be added after ithasRole("ADMIN")checks the authorityROLE_ADMIN;hasAuthority("ROLE_ADMIN")is the same, written in full@PreAuthorizesupports SpEL with the arguments (#athlete) andauthentication;@PostAuthorize, alsoreturnObject@Secureduses the full authority name (ROLE_COACH) and no SpEL;@RolesAllowed(JSR-250) uses the role name- Not authenticated → 401; authenticated without permission → 403
- CSRF is on by default: state-changing methods (POST, PUT, DELETE, PATCH) need a token; GET doesn't
Exam traps
hasRole("ROLE_ADMIN")fails: Spring adds the prefix and would look forROLE_ROLE_ADMIN(in fact it throws when configured)- Putting
requestMatchers("/api/**").authenticated()before a more specific rule overrides it - Method security works with proxies: internal calls (
this) and private methods aren't checked @PostAuthorizeruns the method before checking: it can't prevent side effects- Disabling CSRF only makes sense for stateless APIs (no session or authentication cookies)