Spring Security 配置循环依赖错误

Jou*_*ner 2 dependency-injection spring-security jwt

我有一个有效的自定义 Spring Security 配置,以使用 JSON Web 令牌而不是 HTTPSession 来保护某些 url 模式。

我为了启用与基于 url 模式相反的基于方法的安全性,我需要注册一个 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.
Run Code Online (Sandbox Code Playgroud)

我自己的依赖是我需要的过滤器来配置它。当我省略 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();
    }
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Jou*_*ner 6

只需返回如下所示的 AuthenticationManager 即可解决问题:

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return authenticationManager();
}
Run Code Online (Sandbox Code Playgroud)