spring-security - Spring Security 配置循环依赖错误

标签 spring-security dependency-injection jwt

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

我要启用 method based security与基于 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.

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

我错过了什么?

最佳答案

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

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

关于spring-security - Spring Security 配置循环依赖错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498030/

相关文章:

Spring Security - 未创建默认表

dependency-injection - 如果 Dagger/Hilt 是抽象类或接口(interface),它们在模块中有区别吗?

.net - 我应该使用哪种依赖注入(inject)工具?

security - 如何保护REST-API?

java - jhipster中通过id限制URL访问控制

java - @PreAuthorize 中的 hasRole 在 Spring 中从哪里获取其值?

spring - Grails-使用Spring Security插件通过UI登录时如何使用JWT

java - Spring Security oauth2 客户端

dependency-injection - C# 中的 autofac "Hello World"应用程序 - 初始化

reactjs - Flask 和 React - Spotify 授权后处理 token