Sub topic 10
Protecting Endpoints with Request Rules
This chapter assumes you have a working resource server that validates JWTs, as set up in the earlier chapters. You should also know how claims become GrantedAuthority values (for example SCOPE_orders.read). Here we focus on request rules: the URL-based part of authorization, declared in the SecurityFilterChain.
What a request rule does
A request rule maps a request (path, HTTP method) to an access decision. Spring Security evaluates the rules after the bearer token has been authenticated. The decision is one of three outcomes:
- The request is allowed.
- The caller is not authenticated, so the server answers 401.
- The caller is authenticated but lacks permission, so the server answers 403.
The rules live in authorizeHttpRequests. Each rule has a matcher (which requests it covers) and an access rule (who may pass).
A complete rule set
This is the filter chain from the plan, with each part explained below.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}/public/**is open. No token is required, and if one is sent it is not needed for the decision./admin/**requires the authoritySCOPE_admin. TheSCOPE_prefix is added by the default converter to each value in the token'sscopeclaim.anyRequest().authenticated()is the catch-all. Any other path needs a valid token, with no particular authority.STATELESStells Spring Security not to create an HTTP session. Every request must carry its own token.
Rule order matters
Rules are checked top to bottom, and the first match wins. Later rules are never consulted for that request. This produces a common mistake:
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
.requestMatchers("/public/**").permitAll()) // never reachedSpring Security rejects this at startup because anyRequest() must be last. A subtler version is a broad pattern placed before a narrow one:
.requestMatchers("/orders/**").hasAuthority("SCOPE_orders.read")
.requestMatchers("/orders/export").hasAuthority("SCOPE_orders.export") // shadowedA caller with only orders.read can reach /orders/export, because the first rule matched. Put the most specific rules first.
Matching by HTTP method
Reading and writing often need different permissions. Pass the method to the matcher:
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/orders/**").hasAuthority("SCOPE_orders.read")
.requestMatchers(HttpMethod.POST, "/orders/**").hasAuthority("SCOPE_orders.write")
.requestMatchers(HttpMethod.DELETE, "/orders/**").hasAuthority("SCOPE_admin")
.anyRequest().denyAll())Here anyRequest().denyAll() makes the policy default-deny. A PUT to /orders/1 matches none of the specific rules and is rejected for everyone. This is safer than authenticated() as a fallback, because a new endpoint is blocked until you add a rule for it.
The access rules available
| Rule | Meaning |
|---|---|
| `permitAll()` | Anyone, with or without a token |
| `denyAll()` | Nobody |
| `authenticated()` | Any valid token |
| `hasAuthority("X")` | Authority exactly `X` |
| `hasAnyAuthority("X", "Y")` | At least one of the listed authorities |
| `hasRole("X")` | Authority `ROLE_X` (the prefix is added for you) |
| `access(...)` | A custom `AuthorizationManager` |
The hasRole and hasAuthority pair causes frequent confusion. With the default converter, a scope admin becomes SCOPE_admin, so hasRole("admin") looks for ROLE_admin and fails. If you configured the converter to emit ROLE_ prefixed authorities from a roles claim, use hasRole("ADMIN") for the authority ROLE_ADMIN. Pick the rule that matches your converter.
Matcher patterns
requestMatchers accepts Ant-style path patterns when Spring MVC is on the classpath:
/orders/*matches one path segment, such as/orders/42, but not/orders/42/items./orders/**matches/orders,/orders/42, and everything below./orders/{id}matches one segment and names it.
Be careful with exact paths. Whether /orders/ (trailing slash) matches /orders depends on your Spring MVC configuration. Since Spring Framework 6, trailing slash matching is off by default, so /orders/ is a different path from /orders. Spring Security matches against the same path form that MVC uses, so a rule for /orders does not protect /orders/, but MVC does not route that URL to your controller either. If you enable trailing slash matching yourself, protect both forms or use /orders/**.
You can also give matchers more than one pattern:
.requestMatchers("/actuator/health", "/actuator/info").permitAll()
.requestMatchers("/actuator/**").hasAuthority("SCOPE_ops")The narrow permitAll rule comes first, so health checks stay open while the rest of Actuator needs the ops scope.
Combining conditions
hasAuthority takes one authority. For "scope A and scope B", use access with AuthorizationManagers:
import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasAuthority;
.requestMatchers("/reports/**").access(
AuthorizationManagers.allOf(
hasAuthority("SCOPE_reports.read"),
hasAuthority("SCOPE_finance")))allOf requires every manager to grant access. anyOf requires one. This keeps the rule in the filter chain, but if conditions depend on the data being accessed (for example "only the owner of this order"), a URL rule cannot express it. Use method security with @PreAuthorize, covered in the next chapter.
CSRF and CORS with bearer tokens
Two settings interact with request rules.
CSRF (cross-site request forgery) protection defends cookie-based sessions. A browser attaches cookies automatically, but it does not attach an Authorization header by itself. A stateless API that reads only bearer tokens is therefore not exposed to classic CSRF. Spring Security's resource server support disables CSRF protection for requests that carry a bearer token, so POST requests with a token work without a CSRF token. Do not disable CSRF globally if the same application also serves cookie-based pages.
CORS (cross-origin resource sharing) is different. A browser sends a preflight OPTIONS request without credentials. If your rules require authentication for every request, the preflight gets a 401 and the real request never happens. Enable the CORS support in the chain so it handles preflights before authorization:
http
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated());cors(Customizer.withDefaults()) uses a CorsConfigurationSource bean if you define one, or the MVC CORS configuration otherwise.
Multiple filter chains
A single application can have more than one SecurityFilterChain, each scoped with securityMatcher. The first chain whose matcher fits the request handles it, so order them with @Order.
@Bean
@Order(1)
SecurityFilterChain actuator(HttpSecurity http) throws Exception {
http
.securityMatcher("/actuator/**")
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.anyRequest().hasAuthority("SCOPE_ops"))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}Use separate chains when areas need different settings, such as different token types or error handling. For simple differences in who may call what, one chain with ordered rules is easier to read.
Common errors
- Everything returns 401 even with a token. The token is failing validation (issuer, expiry, signature), not the rules. Check the
WWW-Authenticateheader for the error description. - Always 403 for a valid token. The authority name does not match. Decode the token and compare its
scopeorrolesvalues with what the rule expects, remembering theSCOPE_prefix. - A narrow rule seems ignored. A broader rule above it matched first.
permitAllpaths return 401. The path is covered by a different filter chain, or a malformed token was sent. An invalid bearer token is rejected even onpermitAllpaths, because the token is parsed before the rules run.
Exercise
Your rules are .requestMatchers("/api/**").authenticated() followed by .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin"). A user with a valid token but no admin scope calls /api/admin/users. What status do they get, and how do you fix the rules?
Show answer
They get 200 (the request reaches the controller), because the first rule, /api/** with authenticated(), matches and the admin rule is never evaluated. Fix it by placing the more specific /api/admin/** rule before /api/**. With the right order, the user gets 403.
Exercise
You need DELETE /orders/{id} to require the admin scope, GET /orders/** to require orders.read, and everything else to be rejected. Write the authorizeHttpRequests block.
Show answer
.authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/orders/*").hasAuthority("SCOPE_orders.read") .requestMatchers(HttpMethod.DELETE, "/orders/").hasAuthority("SCOPE_admin") .anyRequest().denyAll())