Sub topic 7
Authorizing requests by path, role and authority
This chapter assumes you can write a Spring Boot REST controller, you know what a @Bean method is, and you have seen a basic SecurityFilterChain. Here you learn how authorizeHttpRequests decides which callers can reach which paths.
The rule list
Authorization rules live in the authorizeHttpRequests block of your SecurityFilterChain. Each rule pairs a request matcher with an access requirement. Spring Security checks the rules in the order you declare them. The first rule whose matcher fits the request decides the outcome, and later rules are never consulted.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/orders/**").hasAnyRole("USER", "ADMIN")
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}Reading from the top:
- Anyone may call
/public/**, even without credentials. - A
GETon/api/orders/**needs theUSERorADMINrole. - Anything under
/api/admin/**needsADMIN. - Every other request needs a logged-in caller.
The final anyRequest() rule is a catch-all. Put it last, because it matches everything.
Roles and authorities
Spring Security stores permissions as authorities, which are plain strings. A role is an authority with the prefix ROLE_. These two checks are equivalent:
| Check | Authority it looks for |
|---|---|
| `hasRole("ADMIN")` | `ROLE_ADMIN` |
| `hasAuthority("ROLE_ADMIN")` | `ROLE_ADMIN` |
| `hasAuthority("SCOPE_orders.read")` | `SCOPE_orders.read` |
Use hasRole and hasAnyRole for coarse groupings of users, and hasAuthority for fine-grained permissions such as OAuth2 scopes. Pass hasRole the name without the prefix. If you write hasRole("ROLE_ADMIN"), Spring Security rejects it at startup.
Order matters
Rules are evaluated top to bottom, so put the most specific rules first. This configuration contains a bug:
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/**").authenticated()
.requestMatchers("/api/admin/**").hasRole("ADMIN"))Any logged-in user matches /api/** first and is allowed in. The admin rule is never reached. Swap the two lines to fix it.
Do not add that block. The next diagram shows the evaluation order.
Denied requests
The rule result produces one of two status codes:
- 401 Unauthorized: the caller is not authenticated. With HTTP Basic, Spring Security also sends a
WWW-Authenticateheader. - 403 Forbidden: the caller is authenticated but lacks the required role or authority.
A request that matches no rule at all is denied by default in the Spring Security 6 authorization model. This is why a closing anyRequest() rule is good practice. It states your intent for every remaining path.
Common mistakes
- Placing
anyRequest().permitAll()first, which opens the whole API. - Writing
/api/orders/*when you need/api/orders/**. The single star matches one path segment only. - Forgetting the HTTP method. A rule without a method covers all methods, so a
DELETEon/api/orders/1can slip through a rule meant forGET. - Using
hasRole("ROLE_USER")instead ofhasRole("USER").
Exercise
A config lists .requestMatchers("/api/**").authenticated() before .requestMatchers("/api/admin/**").hasRole("ADMIN"). A user with only ROLE_USER calls /api/admin/users. What status do they get, and how do you fix the config?
Show answer
They get 200 (the request is allowed), because the first matching rule, /api/** with authenticated(), wins and the admin rule is never evaluated. Fix it by putting the /api/admin/** rule before the /api/** rule. The user then gets 403.