无法访问Actuator健康端点问题求助
问题排查与解决方案
你的问题根源在于自定义JwtAuthenticationFilter在Spring Security授权判断之前就拦截了请求:虽然你在SecurityFilterChain中配置了/actuator/**为permitAll,但自定义过滤器是通过addFilterBefore添加到UsernamePasswordAuthenticationFilter之前的,这个过滤器会对所有请求生效,包括你想要放行的端点,直接抛出了Token缺失的异常,导致请求根本没走到授权校验环节。
解决方法
最直接的方案是在JwtAuthenticationFilter中添加路径判断,跳过不需要Token校验的公共路径(包括/actuator/**):
修改JwtAuthenticationFilter代码
@Component @RequiredArgsConstructor @Slf4j @Profile({"local", "dev", "sit", "uat", "prod"}) public class JwtAuthenticationFilter extends AuthenticationFilter { private final JwtService jwtService; // 用于路径匹配的工具类 private final AntPathMatcher pathMatcher = new AntPathMatcher(); @Override protected void doFilterInternal( @NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { // 先判断是否为公共路径,是则直接放行,不做Token校验 String requestPath = request.getServletPath(); if (isPublicPath(requestPath)) { filterChain.doFilter(request, response); return; } final String jwt = this.getJWT(request); if (StringUtil.isNotBlank(jwt)) { this.validateToken(jwt, request, response); } else { throw new TokenRequiredException("Token not found in request"); } log.info("SecurityContextHolder.getContext() : {}", SecurityContextHolder.getContext()); filterChain.doFilter(request, response); } // 定义所有不需要拦截的公共路径 private boolean isPublicPath(String path) { return pathMatcher.match("/actuator/**", path) || pathMatcher.match("/resources/**", path) || pathMatcher.match("/static/**", path) || pathMatcher.match("/images/**", path) || pathMatcher.match("/javascript/**", path) || pathMatcher.match("/js/**", path) || pathMatcher.match("/fonts/**", path) || pathMatcher.match("/css/**", path); } }
额外注意事项
management.security.enabled配置在Spring Boot 2.x及以上版本已被弃用,你当前的management.endpoints.web.exposure.include=health配置是正确的,无需保留废弃配置。- 确认你的应用
server.servlet.context-path配置:如果上下文路径是/my-service,那么request.getServletPath()返回的是/actuator/health,上述路径匹配逻辑可以正常工作;如果上下文路径为空,同样不影响匹配。
这样修改后,/actuator/health请求会被过滤器直接放行,不会触发Token校验,也就不会返回403和Token缺失的错误了。
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

