anyRequest() is the catch-all authorization matcher in Spring Security. It applies to every HTTP request not matched by an earlier rule, so it belongs at the end of a request-authorization chain. section 8.1 section 7.1.1
Choose the terminal access rule according to the application’s intended default:
- Use anyRequest().permitAll() when every otherwise-unmatched endpoint should be accessible without authentication. section 2.3.2
- Use anyRequest().authenticated() when every otherwise-unmatched endpoint should require a successfully authenticated user. section 8.1
- Use anyRequest().hasAuthority("WRITE") or hasAnyAuthority(...) when the remaining endpoints require specific authorities. section 7.1.1
- Place specific requestMatchers() rules before anyRequest(); placing the general matcher first prevents later specific rules from expressing their intended scope. section 8.1
Protect selected endpoints and define the remainder
A configuration can require ADMIN for /hello, MANAGER for /ciao, and explicitly permit every other request: requestMatchers("/hello").hasRole("ADMIN").requestMatchers("/ciao").hasRole("MANAGER").anyRequest().permitAll(). A request to /hola then returns 200 OK without credentials. Supplying invalid credentials can still produce 401 Unauthorized because authentication occurs before authorization. section 8.1
Listing 8.4 Marking additional requests explicitly as accessible without authentication
@Configuration
public class ProjectConfig {
// Omitted code
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http.httpBasic(Customizer.withDefaults());
http.authorizeHttpRequests(
c -> c.requestMatchers("/hello").hasRole("ADMIN")
.requestMatchers("/ciao").hasRole("MANAGER")
.anyRequest().permitAll() #1
);
return http.build();
}
}
Inspect the complete SecurityFilterChain showing specific role rules followed by anyRequest().permitAll(). section 8.1
