Spring Security配置循环依赖性错误

时间:2015-11-03 11:30:36

标签: spring-security dependency-injection jwt

我有一个有效的自定义Spring安全配置,使用JSON Web令牌而不是HTTPSession保护某些网址模式。

我命令在基于url的模式中启用method based security,我需要注册一个AuthenticationManager,它因循环依赖而失败:

Caused by: org.springframework.beans.BeanInstantiationException: 
Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: 
Factory method 'authenticationManagerBean' threw exception; nested exception is org.springframework.beans.FatalBeanException: 
A dependency cycle was detected when trying to resolve the AuthenticationManager. Please ensure you have configured authentication.

我自己的依赖是我需要一个过滤器来配置它。当我省略AuthenticationManager的注册时,一切正常:

@Configuration
@EnableWebSecurity
@Order(2)
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private StatelessAuthenticationFilter statelessAuthenticationFilter;

    public SpringSecurityConfig() {
        super(true);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        ...
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                ...
                // check specific paths for specific role
                .antMatchers("/...").hasRole("...")
                ...

                // all other calls must be authenticated
                .anyRequest().authenticated().and()

                // custom filter to parse JWT token previously sent to client from header and create Authentication
                .addFilterBefore(statelessAuthenticationFilter, (Class<? extends Filter>) UsernamePasswordAuthenticationFilter.class)

                ...
    }

    // config works fine without this method, but method security needs an AuthenticationManager:
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

我错过了什么?

2 个答案:

答案 0 :(得分:1)

如下所示返回AuthenticationManager修复了问题:

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return authenticationManager();
}

答案 1 :(得分:1)

您必须配置身份验证管理器......如下所示:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.authenticationProvider(new MyCustomAuthProvider());
}