Harshana
Harshana

Reputation: 7647

Two SecurityConfig class in a spring boot project

I have a SecurityConfig class already in a external library I am using.

I want to have another SecurityConfig class in order to register more filters in my project using addFilterBefore and addFilterAfter.

I just add below in my project and I get below error,

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {       
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: @Order on WebSecurityConfigurers must be unique. Order of 100 was already used, so it cannot be used on com.pearson.springtools.config.SecurityConfig$$EnhancerBySpringCGLIB$$f0407fdb@7326eb0d too.

Upvotes: 6

Views: 10082

Answers (3)

burak isik
burak isik

Reputation: 571

Spring boot is already using WebSecurityConfigurerAdapter under root. It doesn't allow to give same order to the second WebSecurityConfigurerAdapter. Giving different order to the second WebSecurityConfigurerAdapter (e.g. order(1000) ) fixed my issue.

Example code:

@Configuration
@EnableWebSecurity
@Order(1000)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   ...
}

Upvotes: 0

Rishabh Pradhan
Rishabh Pradhan

Reputation: 91

Only WebSecurityConfigurerAdapter should be used at a time. If you want to use multiple ones in the same configuration, you have to add the @order annotation on at least one of them to specify the order in which they should be considered. To use the custom one, have it with the highest order.

@Configuration
@EnableWebMvcSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {       
}

Upvotes: 4

Kumar Abhishek
Kumar Abhishek

Reputation: 3124

I had the same issue, apply @Order(99) on your websecurity it will fix.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableAutoConfiguration(exclude = {
        org.activiti.spring.boot.RestApiAutoConfiguration.class,
        org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
        org.activiti.spring.boot.SecurityAutoConfiguration.class})
@ComponentScan(basePackages = {"com.onlineBankingApplication"})
@Order(99)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

Upvotes: 5

Related Questions