2022-02-22

Spring Security: Configuring HttpSecurity

Spring Security 5.4 introduced the ability to configure HttpSecurity by creating a SecurityFilterChain bean.

Below is an example configuration using the WebSecurityConfigurerAdapter that secures all endpoints with HTTP Basic:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
    }

}
Going forward, the recommended way of doing this is registering a SecurityFilterChain bean:

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
        return http.build();
    }

}

No comments:

Post a Comment