Spring Boot集成JWT后如何禁用Actuator端点的JWT安全
解决Spring Security集成JWT后Actuator端点无法访问的问题
嘿,我之前也碰到过一模一样的问题!其实核心就是在Spring Security的配置里给Actuator的端点开个“绿色通道”,让它们跳过JWT验证就行。下面是具体的解决步骤:
1. 编写Spring Security配置类
现在Spring Boot 2.7及以上版本已经废弃了WebSecurityConfigurerAdapter,改用SecurityFilterChain来做配置,直接在你的配置类里添加如下代码:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 配置请求授权规则 .authorizeHttpRequests(auth -> auth // 放行所有Actuator端点的请求,无需JWT验证 .requestMatchers("/actuator/**").permitAll() // 其他所有请求必须经过JWT认证 .anyRequest().authenticated() ) // 这里保留你原来的JWT相关配置(比如JwtAuthenticationFilter) // .addFilterBefore(yourJwtFilter, UsernamePasswordAuthenticationFilter.class) ; return http.build(); } }
关键就是requestMatchers("/actuator/**").permitAll()这一行,它会匹配所有Actuator的端点路径(比如/actuator/health、/actuator/metrics),并允许这些路径无需认证直接访问。
2. 检查你的application.yml配置
你的现有配置已经开启了metrics端点并暴露了health和metrics,不过要确保格式正确(逗号后面的空格不能少):
management: endpoint: metrics: enabled: true endpoints: web: exposure: include: health, metrics
3. 测试验证
配置完后重启项目,直接访问http://localhost:你的项目端口/actuator/health或者/actuator/metrics,应该就能正常返回监控数据了,不需要在请求头里携带JWT Token。
内容的提问来源于stack exchange,提问作者Chrishan
相关产品推荐
相关产品推荐

