Home > Software design >  SecurityFilterChain Bean doesn't protect app
SecurityFilterChain Bean doesn't protect app

Time:08-07

I am in the middle of process of mirgation my Spring Security Configuration from WebSecurityConfigurerAdapter (deprecated) to configuration with beans.

My config class now looks like

@EnableWebSecurity
public class Config {

    @Bean
    protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
        return http.build();
    }

}

I understand that this configuration doesn't make any behavior settings, but shouldn't it return a SecurityFilterChain bean that will act like the default SecurityFilterChain (as if no configuration was specified)? When I start my app no controllers are secured.

CodePudding user response:

The typical way is to extend WebSecurityConfigurerAdapter and override its configure(HttpSecurity http) method:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
/**
   stuff like
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/blog/**").permitAll()
                    .anyRequest().authenticated()
            )
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login")
                    .permitAll()
            );
    
   but NO http.build() at the end!
**/
    }


}

CodePudding user response:

SecurityFilterChain bean method is marked as protected which makes it inaccessible for bean lookup outside your config

Mark SecurityFilterChain bean method as public

To add security rules for endpoints simply add .authorizeRequests() block:

@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public Config filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/unprotected", "/endpoints/**").permitAll()
                .anyRequest().authenticated();
        return http.build();
    }

}

Also read Spring Security without the WebSecurityConfigurerAdapter

  • Related