如何为BearerTokenAuthenticationFilter设置认证失败处理器?
我已通过http.oauth2ResourceServer().jwt()构建过滤器链,且配置了spring.security.oauth2.resourceserver.jwt.issuer-uri,当前请求认证功能正常。现在需要在认证失败时执行自定义日志记录,计划通过自定义认证入口点处理无Bearer Token的场景,结合自定义BearerTokenAuthenticationFilter.authenticationFailureHandler处理无效Token的情况,也接受其他可行方案。
已实现的部分
我已成功配置自定义认证入口点,处理无Token的场景:
// 在WebSecurityConfigurerAdapter::configure中 http .exceptionHandling() .authenticationEntryPoint((request, response, exception) -> { /* 自定义无Token处理逻辑 */ });
遇到的核心问题
我找不到直接访问Spring Security自动创建的BearerTokenAuthenticationFilter的方式。目前想到的折中方案是新建一个配置好自定义失败处理器的BearerTokenAuthenticationFilter,并添加到原有过滤器之前,但这会导致每个成功认证的请求都额外执行一次处理,并非最优解:
// 在WebSecurityConfigurerAdapter::configure中 var filter = new BearerTokenAuthenticationFilter(authenticationManagerBean()); filter.setAuthenticationFailureHandler(new JwtAuthenticationFailureHandler()); http.addFilterBefore(filter, BearerTokenAuthenticationFilter.class); // 自定义过滤器会优先执行
尝试过的其他方案
理论上应该有办法为Spring Security自动创建的过滤器设置该属性,本以为OAuth2ResourceServerConfigurer会提供相关配置,但它仅支持配置accessDeniedHandler。
我尝试过直接获取过滤器本身或DefaultSecurityFilterChain作为Bean,但它们不存在于应用上下文。之前看到一个方案建议通过BeanPostProcessor处理,但尝试后未成功——按照建议修改spring-servlet.xml配置了命名为filterChain的http节点,依然无法通过getBean找到该Bean,也没能被BeanPostProcessor识别:
<http name="filterChain">
内容的提问来源于stack exchange,提问作者Floegipoky

