IllegalStateException:无法应用于已构建的对象

时间:2017-08-30 23:04:16

标签: java spring spring-boot spring-security

我在版本1.5.6.RELEASE

中使用spring-boot

我得到了以下异常。

Caused by: java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer@6b5c38ed to already built object
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.add(AbstractConfiguredSecurityBuilder.java:196)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.apply(AbstractConfiguredSecurityBuilder.java:133)
    at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.apply(AuthenticationManagerBuilder.java:290)
    at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.inMemoryAuthentication(AuthenticationManagerBuilder.java:134)
    at com.mca.security.configurer.auth.FirstAuthenticationManagerConfigurer.configure(FirstAuthenticationManagerConfigurer.java:12)
    at com.mca.security.configurer.auth.FirstAuthenticationManagerConfigurer.configure(FirstAuthenticationManagerConfigurer.java:7)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.configure(AbstractConfiguredSecurityBuilder.java:384)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:330)

我设法在这里重现它:

https://github.com/mironbalcerzak/spring-boot-security-issue

实施背后的想法非常简单。 我希望创建一些SecurityConfigurer(用于HttpSecurity和AuthenticationManagerBuilder),并在扩展WebSecurityAdapter的类中使用apply()进行组合。

如果我错了,请纠正我,而且不是这样做的。

我找到的解决方法是提取"应用" SecurityConfigurerAdapter.init(...)的方法,以及对已创建的对象进行操作的SecurityConfigurerAdapter.configure(...)。

这是解决方法(这让我非常不开心:))

public class FirstAuthenticationManagerConfigurer
        extends SecurityConfigurerAdapter<AuthenticationManager, AuthenticationManagerBuilder> {

    private DaoAuthenticationConfigurer<AuthenticationManagerBuilder, UserDetailsManager> configurer;

    @Override
    public void init(AuthenticationManagerBuilder builder) throws Exception {
        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> managerConfigurer = builder.inMemoryAuthentication();
        managerConfigurer.withUser("user1").password("password").roles("SYSTEM");
        UserDetailsManager userDetailsService = managerConfigurer.getUserDetailsService();
        configurer = builder.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        configurer.configure(builder);
    }
}

...有个好日子和快乐的编码:)

1 个答案:

答案 0 :(得分:0)

尝试在带有configureGlobal(AuthenticationManagerBuilder auth)注释的配置中使用@EnableWebSecurity

https://github.com/spring-projects/spring-data-examples/issues/189