AuthenticationProcessingFilter和WebSecurityConfigurerAdapter导致循环依赖

时间:2018-09-26 05:57:23

标签: java spring

在我的Spring启动应用程序中,我有以下两个类:

@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        // TODO re-enable csrf after dev is done
        .csrf()
            .disable()
            // we must specify ordering for our custom filter, otherwise it
            // doesn't work
            .addFilterAfter(jwtAuthenticationFilter,
                    UsernamePasswordAuthenticationFilter.class)
            // we don't need Session, as we are using jwt instead. Sessions
            // are harder to scale and manage
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
   }
}

和:

@Component
public class JwtAuthenticationFilter extends
        AbstractAuthenticationProcessingFilter {

    /*
     * we must set authentication manager for our custom filter, otherwise it
     * errors out
     */
    @Override
    @Autowired
    public void setAuthenticationManager(
            AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }
}

JwtAuthenticationFilter通过其AuthenticationManager方法依赖于setAuthenticationManager bean,但是该bean是在AppSecurityConfig中创建的,而JwtAuthenticationFilter已自动插入。创建循环依赖。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

我按照以下建议解决了此问题: Cannot pass AuthenticationManager to custom filter by @Autowired

我从@Component中删除了JwtAuthenticationFilter,而不是将JwtAuthenticationFilter自动装配到WebSecurityConfig类,而是在那里定义了bean:

@Bean
public JwtAuthenticationFilter JwtAuthenticationFilter() {
    return new JwtAuthenticationFilter();
}