在我的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
已自动插入。创建循环依赖。
我该如何解决这个问题?
答案 0 :(得分:5)
我按照以下建议解决了此问题: Cannot pass AuthenticationManager to custom filter by @Autowired
我从@Component
中删除了JwtAuthenticationFilter
,而不是将JwtAuthenticationFilter
自动装配到WebSecurityConfig
类,而是在那里定义了bean:
@Bean
public JwtAuthenticationFilter JwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}