JWTAuthenticationFilter

JWTAuthenticationFilter

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

@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创建的。这整个事情创建了一个循环依赖性。
我应该如何解决这个问题?

最佳答案

我按照这里的建议解决了这个问题:
Cannot pass AuthenticationManager to custom filter by @Autowired

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

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

10-06 14:03