正如大家所知,WebSecurityConfigurerAdapter类已被废弃。
我尝试在我的filterChain中实现customFilter,但是我遇到了一个与新的AuthenticationManager相关的问题。
问题就在这里:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.sessionManagement().sessionCreationPolicy(STATELESS);
http.authorizeRequests().anyRequest().permitAll();
http.addFilter(new CustomAuthenticationFilter(authenticationManager()));
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
如您所见,Authentication Manager需要AuthenticationConfiguration类作为NotNull参数,如果没有它,我将无法创建CustomAuthenticationFilter。
有人遇到过这个问题吗?我需要为AuthenticationConfiguration创建一个新的@Bean吗?
下面是我的CustomAuthenticationFilter类:
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
public CustomAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String username = request.getParameter("username");
String password = request.getParameter("password");
log.info("Userame is {}", username);
log.info("passoword is {}", password);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
return authenticationManager.authenticate(authenticationToken);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
}
}
1条答案
按热度按时间r7s23pms1#
由于
AuthenticationConfiguration
是由spring-boot自动注册为bean的,因此您可以将其作为config类字段而不是bean定义方法的参数注入,如下所示: