Sub topic 7
Authorizing requests by path, role and authority
Authentication tells Spring Security who is calling. Authorization decides what that caller may do. This chapter covers the HTTP-level part of authorization, which you configure with authorizeHttpRequests inside a SecurityFilterChain. It assumes you have a working filter chain bean from the earlier chapters, know how users and GrantedAuthority values end up in the SecurityContext, and can read a Java lambda DSL.
How authorization rules are evaluated
authorizeHttpRequests builds an ordered list of rules. Each rule pairs a request matcher with an authorization requirement. For every request that reaches the AuthorizationFilter (the last filter in the chain), Spring Security walks the list from top to bottom and applies the first rule whose matcher fits. It ignores all later rules. If no rule matches, the request is denied.
Two consequences follow from first-match-wins:
- Order matters. Put specific rules before general ones.
anyRequest()must be last. Spring Security rejects a configuration that declares more rules after it.
A complete rule set
The following configuration is a full class. It builds on the stateless Basic setup from earlier chapters.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**", "/error").permitAll()
.requestMatchers("/internal/**").access((authentication, context) ->
new AuthorizationDecision(
"127.0.0.1".equals(context.getRequest().getRemoteAddr())))
.requestMatchers(HttpMethod.GET, "/api/orders/**").hasAnyRole("USER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/api/orders").hasRole("USER")
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/actuator/**").denyAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}Each line uses a different tool:
permitAll()lets everyone through, including anonymous callers. Permitting/errormatters because the servlet container forwards failures there. If/errorneeds authentication, a real 404 or 500 can turn into a confusing 401.access(...)takes anAuthorizationManager, which is any function from the current authentication and request to anAuthorizationDecision. Use it for rules the built-in methods can't express, such as the loopback-address check above.hasAnyRole,hasRolecheck for roles.denyAll()blocks a path for everyone. It is a safe default for endpoints you never want exposed.authenticated()requires any logged-in caller, regardless of role.
Matching paths
requestMatchers accepts Ant-style patterns, and optionally an HttpMethod to narrow the match.
| Pattern | Matches | Does not match |
|---|---|---|
| `/api/orders` | `/api/orders` | `/api/orders/42`, `/api/orders/` |
| `/api/orders/*` | `/api/orders/42` | `/api/orders/42/items` |
| `/api/orders/**` | `/api/orders`, `/api/orders/42`, `/api/orders/42/items` | `/api/order` |
| `/api/*/items` | `/api/orders/items` | `/api/orders/42/items` |
When Spring MVC is on the classpath, requestMatchers builds matchers that follow MVC's own path-matching rules. Since Spring Framework 6, MVC no longer treats /api/orders and /api/orders/ as the same URL. The controller mapping and your security rule then agree on what is matched. A request your controller doesn't serve at a path can't slip past a rule that guards it.
Roles versus authorities
Spring Security stores everything a user may do as GrantedAuthority strings. A role is an authority with the prefix ROLE_. The two families of methods differ only in how they treat that prefix.
| Method | What it compares | Authority needed |
|---|---|---|
| `hasRole("ADMIN")` | Adds the `ROLE_` prefix | `ROLE_ADMIN` |
| `hasAnyRole("USER", "ADMIN")` | Adds the prefix to each name | `ROLE_USER` or `ROLE_ADMIN` |
| `hasAuthority("ROLE_ADMIN")` | Exact string | `ROLE_ADMIN` |
| `hasAuthority("SCOPE_orders.read")` | Exact string | `SCOPE_orders.read` |
| `hasAnyAuthority("report:read", "report:write")` | Exact string, any of the listed | Either one |
The earlier user configuration calls .roles("USER"), which stores ROLE_USER. The matching rule is therefore hasRole("USER"). If you pass "ROLE_USER" to hasRole, Spring Security throws an IllegalArgumentException at startup, because it expects the name without the prefix.
A JWT resource server follows the same logic. Spring turns each space-separated value in the token's scope claim into an authority with the SCOPE_ prefix. A token with scope: "orders.read" yields SCOPE_orders.read, so you check it with hasAuthority. Using hasRole there never matches, because no ROLE_ authority exists.
Prefer roles for coarse, user-facing groupings such as USER and ADMIN. Prefer authorities for fine-grained permissions such as invoice:approve, or for scopes that arrive in tokens.
Role hierarchies
Without further configuration, an admin who should also be allowed to do everything a user can must carry both roles. A RoleHierarchy bean states the implication once. This example uses the builder available in Spring Security 6.3 and later.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
@Configuration
public class RoleConfig {
@Bean
RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.withDefaultRolePrefix()
.role("ADMIN").implies("USER")
.build();
}
}With this bean, a user holding only ROLE_ADMIN passes hasRole("USER") checks. In some versions, method security needs a separate hierarchy-aware expression handler. Verify the behavior with a test before relying on it for @PreAuthorize.
Choosing a default for unmatched requests
The final rule decides what happens to every path you forgot. Two common choices give opposite security postures:
anyRequest().authenticated()allows any logged-in user to reach unlisted paths. It is convenient, and acceptable when every authenticated user is meant to see most endpoints.anyRequest().denyAll()blocks everything not explicitly allowed. It is stricter. A new controller stays unreachable until someone adds a rule, which makes accidental exposure unlikely.
For APIs with several roles, the deny-by-default style catches forgotten endpoints during testing instead of in production.
What the caller sees: 401 and 403
A denied request produces one of two statuses, and the difference tells the client what to do next.
- 401 Unauthorized means no valid credentials were provided. The
AuthenticationEntryPointproduces it. WithhttpBasic, the response carries aWWW-Authenticate: Basicheader. - 403 Forbidden means the caller is authenticated but lacks the needed authority. The
AccessDeniedHandlerproduces it.
Spring decides between them by checking whether the current authentication is anonymous. A request with a valid password for a user who lacks ADMIN receives 403 on /api/admin/**. A request with no credentials for that same path receives 401. Another chapter shows how to customize both responses.
Common mistakes
- Broad rule first.
.requestMatchers("/api/**").authenticated()placed above/api/admin/**means the admin rule never runs. - Using
ROLE_inhasRole. Pass"ADMIN", or usehasAuthority("ROLE_ADMIN"). - Expecting roles from a JWT. Tokens usually yield
SCOPE_authorities unless you configure a customJwtAuthenticationConverter. - Securing the URL but not the other URL forms. Keep matchers aligned with your controller mappings. Let the MVC-aware matching help you, and test the unlisted variants such as a trailing slash or other methods.
- Blocking
/error. Unrelated server errors then show up as 401 responses.
Exercise
A controller exposes GET /api/reports and DELETE /api/reports/7. The filter chain contains, in this order: .requestMatchers("/api/**").authenticated(), then .requestMatchers(HttpMethod.DELETE, "/api/reports/**").hasRole("ADMIN"), then .anyRequest().denyAll(). A user with only ROLE_USER and valid credentials sends the DELETE request. What status do they get, and how do you fix the configuration so the request is refused?
Show answer
The user gets a successful response (the controller runs). The first rule, /api/** with authenticated(), matches the request first, and the user is authenticated, so the later admin rule is never evaluated. To fix it, move the DELETE /api/reports/** rule above the general /api/** rule, so the specific rule matches first and returns 403 for a user without ROLE_ADMIN.
Exercise
A resource server validates JWTs that contain the claim "scope": "orders.read orders.write". Which authorizeHttpRequests call restricts POST /api/orders to tokens with the write scope?
Show answer
.requestMatchers(HttpMethod.POST, "/api/orders").hasAuthority("SCOPE_orders.write"). Spring maps each scope value to an authority with the SCOPE_ prefix. hasRole would look for ROLE_ authorities and never match.