Home > Mobile >  Reason for @EnableWebSecurity in the configuration class
Reason for @EnableWebSecurity in the configuration class

Time:02-20

I just read answer from the another question What is the use of @EnableWebSecurity in Spring?, but i couldn't understand why we need to add @EnableWebSecurity annotation at all.

Even I remove the @EnableWebSecurity from the configuration, my application still works.

Let's assume that we are going to implement either JWT based (rest api) or simply login based mvc application. For the following configuration what i am missing?

@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        return new MyCustomUserDetailsService();
    }

    @Bean
    public PasswsordEncoder passwsordEncoder() {
        return new BrcyptPasswordEncoder();
    }
 

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // for the jwt authentication add jwt filter etc ..
        // for the login based, override default login page, error page etc..
    }
}

CodePudding user response:

If you are not using spring-boot but just a pure spring project , you definitely need to add @EnableWebSecurity in order to enable spring-security.

But if you are using spring-boot 2.0 , you do not need to add it by yourself because the spring-boot auto configuration will automatically do it for you if you forget to do so. Under the cover , it is done by the WebSecurityEnablerConfiguration which its javadoc also states this behaviour as follows:

If there is a bean of type WebSecurityConfigurerAdapter, this adds the @EnableWebSecurity annotation. This will make sure that the annotation is present with default security auto-configuration and also if the user adds custom security and forgets to add the annotation.

  • Related