[英]Implementing new CustomFilter In Spring Security
眾所周知,WebSecurityConfigurerAdapter class 已被棄用。
我正在嘗試在我的 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 class 作為 NotNull 參數,沒有它我無法創建 CustomAuthenticationFilter。
有人遇到過這個問題嗎? 我需要為 AuthenticationConfiguration 創建一個新的@Bean 嗎?
這是我的 CustomAuthenticationFilter Class:
@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);
}
}
由於AuthenticationConfiguration
由 spring-boot 自動注冊為 bean,因此您可以將其作為配置 class 字段而不是作為 bean 定義方法的參數注入,如下所示:
@RequiredArgsConstructor
@Configuration
public class AppSecurityConfig {
private final AuthenticationConfiguration authenticationConfiguration;
@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() throws Exception {
return this.authenticationConfiguration.getAuthenticationManager();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.