如何在Spring Security中为不同端口的Actuator与服务配置统一基础路径
最佳实践:将Actuator独立部署在8090端口并统一基础路径
当前配置
应用配置
# Server server.servlet.contextPath=/myapp/api server.port=8080 # Actuator port management.health.probes.enabled=true management.server.port=8090 management.endpoints.web.base-path=/myapp/api/actuator management.metrics.export.prometheus.enabled=true
安全授权配置
@Bean fun filterChain(http: HttpSecurity): SecurityFilterChain { http.authorizeHttpRequests() .requestMatchers(HttpMethod.GET, "/actuator/health").permitAll() // 之前所有服务在8080时可用,现在需令牌 .requestMatchers(HttpMethod.GET, "/myapp/api/actuator/health").permitAll() // 之前Actuator在不同端口时无需令牌可用 .requestMatchers(HttpMethod.GET, "/vehicles/**").permitAll() .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .jwtAuthenticationConverter(jwtAuthenticationConverter()) return http.build() }
需求说明
此前所有服务均运行在8080端口,现在需要将Actuator部署在8090端口,且主服务(8080)与Actuator(8090)的基础路径均需以/myapp/api/开头。
最佳实践方案
1. 优化配置文件,统一基础路径规范
调整Actuator的配置,通过management.server.servlet.contextPath统一基础路径,避免端点路径冗余:
# Server server.servlet.contextPath=/myapp/api server.port=8080 # Actuator配置 management.health.probes.enabled=true management.server.port=8090 management.server.servlet.contextPath=/myapp/api # 给Actuator设置统一的基础路径 management.endpoints.web.base-path=/actuator # 保持端点基础路径为默认值 management.metrics.export.prometheus.enabled=true
配置后路径示例:
- 主服务接口:
http://localhost:8080/myapp/api/vehicles/1 - Actuator健康检查:
http://localhost:8090/myapp/api/actuator/health
完全满足基础路径统一要求,配置逻辑更清晰。
2. 拆分安全配置,区分主服务与Actuator规则
主服务和Actuator使用不同端口,Spring Security默认过滤器链仅拦截主服务请求,需单独配置Actuator的安全规则:
主服务安全配置
负责处理8080端口的业务接口,保留原有业务授权规则:
@Bean @Order(1) fun mainServerFilterChain(http: HttpSecurity): SecurityFilterChain { http.securityMatcher("/myapp/api/**") // 仅匹配主服务路径 .authorizeHttpRequests { auth -> auth.requestMatchers(HttpMethod.GET, "/myapp/api/vehicles/**").permitAll() .anyRequest().authenticated() } .oauth2ResourceServer { oauth -> oauth.jwt { jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()) } } return http.build() }
Actuator安全配置
专门处理8090端口的Actuator端点,按需配置权限:
@Bean @Order(2) fun actuatorServerFilterChain(http: HttpSecurity): SecurityFilterChain { http.securityMatcher("/myapp/api/actuator/**") // 匹配Actuator路径 .authorizeHttpRequests { auth -> auth.requestMatchers(HttpMethod.GET, "/myapp/api/actuator/health").permitAll() // 健康检查允许匿名访问 .anyRequest().authenticated() // 其他Actuator端点需认证 } .oauth2ResourceServer { oauth -> oauth.jwt { jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()) } } return http.build() }
方案优势
- 配置清晰:通过
contextPath统一管理基础路径,避免硬编码冗余 - 安全隔离:主服务与Actuator的安全规则拆分,权限控制更精准
- 规范合规:遵循Spring Boot Actuator最佳配置实践,路径结构易维护
内容的提问来源于stack exchange,提问作者Hodl
相关产品推荐
相关产品推荐

