permitAll() is an endpoint-authorization rule that allows every matched request, whether authenticated or unauthenticated. Combined with anyRequest(), it makes all endpoints accessible without credentials. section 2.3.2 section 7.1.1
Configure it inside authorizeHttpRequests() on a SecurityFilterChain. With Spring Security’s HTTP Basic configuration retained, the rule changes authorization; it does not remove authentication processing. section 2.3.2 section 7.2
Permit public endpoints while protecting selected paths
http.authorizeHttpRequests(c -> c.requestMatchers("/hello").hasRole("ADMIN").requestMatchers("/ciao").hasRole("MANAGER").anyRequest().permitAll()); This configuration protects /hello and /ciao while explicitly allowing every other request, such as /hola. Place the general anyRequest() rule after the more specific matchers. section 8.1
Use permitAll() with these expectations:
- Call a permitted endpoint without credentials and receive the endpoint response, such as 200 OK and “Hola!”. section 8.1
- Supply valid credentials and still receive access because authentication does not make the permitAll() rule restrictive. section 8.1
- Supply invalid credentials and receive 401 Unauthorized: authentication can fail before authorization applies the public rule. section 8.1
- Prefer explicit rules for public endpoints instead of relying on defaults, and order request matchers from particular to general. section 8.1
Listing 2.8 Using permitAll() to change the authorization configuration
@Configuration
public class ProjectConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http)
throws Exception {
http.httpBasic(Customizer.withDefaults());
http.authorizeHttpRequests(
c -> c.anyRequest().permitAll() #1
);
return http.build();
}
// Omitted code
}
Inspect the complete SecurityFilterChain configuration that applies permitAll() to every request. section 2.3.2
