Spring Boot @ExceptionHandler无法拦截AuthenticationException异常
为什么@ExceptionHandler无法拦截AuthenticationException
@ControllerAdvice仅能拦截已进入DispatcherServlet处理流程后,由Controller层、业务请求链路抛出的异常AuthenticationException(比如错误登录凭据触发的认证异常)是由Spring Security的认证过滤器(如BasicAuthenticationFilter)在请求进入DispatcherServlet之前抛出的,这类异常会被Security链路中的ExceptionTranslationFilter直接接管,根本不会走到@ControllerAdvice的拦截范围- 你配置里虽然写了
.exceptionHandling(),但没有传入任何自定义处理逻辑,框架还是使用默认的入口点生成标准401响应,整个处理过程完全绕开了Servlet层的全局异常处理器,因此自定义逻辑永远不会被触发
调整方案
因为Security层的异常不会进入Servlet处理管线,需要直接在Security的异常处理配置中替换默认组件,才能返回自定义结构的JSON响应:
第一步:实现自定义的认证异常响应组件
创建AuthenticationEntryPoint实现类,统一处理所有认证失败的场景,直接输出你定义的ServiceError结构:
@Component public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { private final ObjectMapper objectMapper; // 复用Spring容器中已有的JSON序列化规则,保证输出格式统一 public CustomAuthenticationEntryPoint(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { ServiceError error = new ServiceError( ServiceErrorCode.REQUEST_INVALID, authException.getMessage() ); response.setStatus(HttpStatus.BAD_REQUEST.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); objectMapper.writeValue(response.getWriter(), error); } }
第二步:将自定义组件注入Security配置
替换原有配置里的默认异常处理逻辑,把自定义的入口点绑定到Security的异常处理链中:
@Configuration public static class ServiceWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; public ServiceWebSecurityConfigurationAdapter(CustomAuthenticationEntryPoint customAuthenticationEntryPoint) { this.customAuthenticationEntryPoint = customAuthenticationEntryPoint; } @Override public void configure(HttpSecurity http) throws Exception { http. csrf().disable(). exceptionHandling() // 绑定自定义认证异常处理逻辑,替换默认401响应 .authenticationEntryPoint(customAuthenticationEntryPoint) .and(). headers().frameOptions().disable(). and(). sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS). and(). authorizeRequests(). antMatchers("/service/**").authenticated(). antMatchers("/health").permitAll(). antMatchers("/metrics").permitAll(). antMatchers("/info").hasAuthority(AuthoritiesConstants.ADMIN). anyRequest().authenticated().and().httpBasic(); } }
补充说明
- 你原来
GlobalExceptionHandler中针对Exception.class的兜底逻辑是可以正常生效的,因为这类异常是在Controller层抛出的,在DispatcherServlet的处理链路内,会被@ControllerAdvice正常拦截 - 若后续需要自定义权限不足(
AccessDeniedException)的响应,只需要按照同样的方式实现自定义AccessDeniedHandler,绑定到exceptionHandling配置块中即可,不需要修改全局异常处理器 - 仅调整@ControllerAdvice的优先级(比如你设置的最高优先级)是无法解决问题的,本质是异常抛出的链路层级和@ControllerAdvice的拦截范围不匹配,两者根本不在同一个执行管线中
内容的提问来源于stack exchange,提问作者PUG
相关产品推荐
相关产品推荐

