authorizeHttpRequests is an HttpSecurity configuration method for defining authorization rules at the HTTP endpoint level. Pair it with an authentication mechanism such as HTTP Basic, then specify whether matching requests are open, authenticated, or restricted by authorities. section 2.3.2
Common authorization rules include:
- anyRequest() applies the following rule to every request, regardless of URL or HTTP method. section 7.1.1
- permitAll() allows matched requests without authentication. section 2.3.2
- authenticated() requires the request to be authenticated. section 2.3.2
- hasAuthority() permits users with one named authority, while hasAnyAuthority() accepts any authority from the supplied list. section 7.1.1
- access() evaluates an authorization expression, such as requiring WRITE authority or combining read and delete checks. section 7.1.1
Restrict every endpoint by authority
Configure HTTP Basic authentication and require WRITE authority for every request: http.authorizeHttpRequests(c -> c.anyRequest().hasAuthority("WRITE")); A user with WRITE receives the endpoint response, while an authenticated user without it receives HTTP 403 Forbidden. section 7.1.1
Listing 2.7 Using the HttpSecurity parameter to alter the configuration
@Configuration
public class ProjectConfig {
@Bean
SecurityFilterChain configure(HttpSecurity http)
throws Exception {
http.httpBasic(Customizer.withDefaults()); #1
http.authorizeHttpRequests(
c -> c.anyRequest().authenticated() #2
);
return http.build();
}
// Omitted code
}
See the complete SecurityFilterChain configuration using HttpSecurity, HTTP Basic, authorizeHttpRequests, authenticated(), and the Customizer lambda. section 2.3.2
