34

I've tried to register multiple filters in my Spring Security Configuration, however I always get the same exception:

04-Nov-2015 14:35:23.792 WARNING [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.AnnotationConfigWebApplicationContext.refresh Exception encountered during context initialization - cancelling refresh attempt 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.payment21.webapp.MultiHttpSecurityConfig$ApiWebSecurityConfigurationAdapter$$EnhancerBySpringCGLIB$$35c79fe4@1d381684 too.

Since my own attempts didn't work, I tried the exact same code as shown in the Spring Security reference:

@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) { 
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }

    @Configuration
    @Order(1)                                                        
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")                               
                .authorizeRequests()
                    .anyRequest().hasRole("ADMIN")
                    .and()
                .httpBasic();
        }
    }

    @Configuration                                                   
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();
        }
    }
}

To isolate the error I tried to replace the web.xml by a Java based approach, but it didn't work either. I have no idea what's wrong, is the doc wrong? Can something in my application mess with the configuation? System is starting up properly, unless I register a second WebSecurityConfigAdapter.

Those are my dependencies:

compile 'org.springframework:spring-webmvc:4.2.2.RELEASE'
compile 'org.springframework:spring-messaging:4.2.2.RELEASE'
compile 'org.springframework:spring-websocket:4.2.2.RELEASE'
compile 'org.springframework:spring-aop:4.2.2.RELEASE'
compile'javax.servlet:javax.servlet-api:3.0.1'
compile 'org.springframework.security:spring-security-web:4.0.3.RELEASE'
compile 'org.springframework.security:spring-security-config:4.0.3.RELEASE'
Journeycorner
  • 2,474
  • 3
  • 19
  • 43

15 Answers15

30

Maybe you have annotated another class with the @EnableWebSecurity annotation. Be aware that only one class can implement this annotation. Hope that will help!

Guchelkaben
  • 1,205
  • 1
  • 12
  • 18
19

It may be worth noting, the @Order annotation should be at the class level. This is a bit confusing since @Journeycorner configuration is a multiclass example. My example with imports :)

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.someco.entity.User;
import com.someco.service.SpringDataJpaUserDetailsService;

@Configuration("CustomSecurityConfig")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(1000)                                                        
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private SpringDataJpaUserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(this.userDetailsService)
            .passwordEncoder(User.PASSWORD_ENCODER);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/built/**", "/main.css").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .defaultSuccessUrl("/", true)
            .permitAll()
            .and()
        .httpBasic()
            .and()
        .csrf().disable()
        .logout()
            .logoutSuccessUrl("/");
}

}
Paul Lungu
  • 259
  • 3
  • 4
16

I have found the error... noone ever posts imports in snippets. We are using a multi module project setup, and IntelliJ didn't recognise the Spring annotations and used

org.apache.logging.log4j.core.config.Order

instead of

org.springframework.core.annotation.Order

Since Spring didn't parse the correct annotations, it was assuming the default value 100 for both configurations.

Journeycorner
  • 2,474
  • 3
  • 19
  • 43
  • That's some deep stuff.. :-) – We are Borg Nov 04 '15 at 15:16
  • 6
    How did you resolve this? I have the exact problem when compiling with IDEA. I have no @Order in my application, yet still it's getting very confused on the WebSecurityConfigurerAdapter! – Thomas Beauvais Jul 18 '16 at 15:36
  • 2
    Use the ```@Order(1000)``` in the SecurityConfiguration class – Ullas Hunka Jan 07 '20 at 06:49
  • @ThomasBeauvais, You probably solved it already but for future reference. Your issue are not caused by bad use of Ordet but the lack of it. When no order are specified Configuration defaults to Order(100). So if you have several classes extending WebSecurityConfigurerAdapter or like me and Journeycorner imports the wrong Order annotation class you get this error. – Mattias Lindblom Sep 16 '21 at 14:00
7

Usually, this exception occurs when the same bean is resolved twice. For example if a @Configuration file imports an applicationContext.xml that resolve the same bean, when the application starts tries to register it (in your case MultiHttpSecurityConfig) twice, and you get this error.

I resolved the error removing the bean definition from the XML.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
A. Saladino
  • 91
  • 1
  • 3
  • I had the security bean resolved twice. Once being loaded by a `@ComponentScan` annotation that included the directory containing the security bean. And another time by the `@SpringBootApplication` annotation that is sitting in that same directory. After removing the directory include attribute, the issue was gone. – Stephane Jul 13 '18 at 09:33
  • which directory you are talking about? – chirag soni Apr 22 '20 at 12:49
4

Putting @Order(1000) on the second WebSecurityConfigurerAdapter worked for me

2

Maybe you have annotated another class with the @EnableWebSecurity annotation. Be aware that only one class can implement this annotation. Hope that will help!

package com.ie.springboot.configuaration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("{noop}123456").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/*").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
                .and().formLogin();
        http.csrf().disable();

    }
}
1

My issue got solved when I added this description to the Security Config:

@Configuration("MySecurityConfig")
public class MySecurityConfig extends WebSecurityConfigurerAdapter
Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
Arun
  • 11
  • 3
1

I recently encountered the same issue but wasn't able to find an answer anywhere to point me in the right direction. I ended up retracing my steps through git history to find that the only change made was adding @RefreshScope annotation to my class.

By removing the @RefreshScope annotation my application worked.

1

It is because Spring security uses WebSecurityConfigurerAdapter under the hood and this adaptor is using order(100), hence spring won't allow duplicate order sequence.

rogue lad
  • 2,413
  • 2
  • 29
  • 32
1

In my case, I had put the @EnableOAuth2Sso annotation on the class annotated with @SpringBootApplication, but I also had a separate class extending WebSecurityConfigurerAdapter. As the documentation of @EnableOAuth2Sso says:

If there is an existing WebSecurityConfigurerAdapter provided by the user and annotated with @EnableOAuth2Sso, it is enhanced by adding an authentication filter and an authentication entry point. If the user only has @EnableOAuth2Sso but not on a WebSecurityConfigurerAdapter then one is added with all paths secured.

Since a default adapter was being added, I ended up with two, which caused the exception.
The solution was of course to move the @EnableOAuth2Sso annotation to the class which extended WebSecurityConfigurerAdapter.

nonzaprej
  • 1,322
  • 2
  • 21
  • 30
1

In my case, I had 2 tags @EnableWebSecurity and @EnableGlobalMethodSecurity(securedEnabled = true). When I removed @EnableWebSecurity tag the problem got solved.

Dharman
  • 30,962
  • 25
  • 85
  • 135
boozy
  • 315
  • 1
  • 8
0

You might be having configuration with @order(100) annotation somewhere in you spring configuration. try removing @order(100) annotation or give some other order value.

Imrank
  • 1,009
  • 5
  • 15
0

I had the same problem and I resolved this error moving @Configuration annotation to class level.

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 
sampathlk
  • 338
  • 2
  • 17
0

In my case, there was another security config class that is established in the parent project. I used excludeFilters tag to exclude the parent security config class and I add my config class spring directly use that config class.

@ComponentScan(basePackages = {
        "com.example.parentProject",  // this is the package that have securit config staff
        
},
        excludeFilters = {@ComponentScan.Filter(
                type = FilterType.ASSIGNABLE_TYPE,
                value = { 
                           SecurityConfig.class //which is inhareted from the parent package
                     })
        })

public class SpringApp{
.....

}
Yusuf Şengün
  • 284
  • 3
  • 13
0

All enabling features should be in main SpringApplication.run(Myclass.class, args);

In my case, I have ZuluConfiguration and KeyCloakConfiguration so I have enabled those configurations under the main class of springbootapplication annotation. it resolved my problem.

@SpringBootApplication
@EnableZuulProxy
@KeycloakConfiguration