Spring Boot 3.2.1迁移后,如何对授权用户隐藏Actuator特定端点值?
Spring Boot 3.2.x Actuator 隐藏特定敏感值的实现方案
可以实现对已授权用户隐藏/actuator/env和/actuator/configprops端点中的特定值,以下是几种可行方案:
1. 用@Secret注解标记敏感配置项
针对自定义@ConfigurationProperties类中的敏感字段,直接添加@Secret注解(Spring Boot 3.1+支持),标记后该字段的值会在Actuator端点中自动被屏蔽为***,无论是否为授权用户。
示例代码:
@ConfigurationProperties(prefix = "my.app") public class MyAppProperties { // 正常展示的配置项 private String apiUrl; // 会被屏蔽的敏感配置项 @Secret private String apiToken; }
2. 通过配置属性指定敏感Key
在配置文件中直接指定需要屏蔽的配置Key,支持通配符匹配,匹配到的Key对应的值会被屏蔽。
示例YAML配置:
management: endpoint: env: sensitive-keys: - "my.app.api-token" - "*password*" - "*secret*" configprops: sensitive-keys: - "my.app.apiToken" - "*token*"
3. 自定义SanitizingFunction实现灵活屏蔽规则
如果需要更复杂的屏蔽逻辑(比如根据值的内容、特定正则匹配等),可以实现SanitizingFunction接口并注册为Spring Bean,该函数会对所有Actuator端点的输出进行 sanitize 处理。
示例代码:
import org.springframework.boot.actuate.endpoint.SanitizingFunction; import org.springframework.stereotype.Component; import java.util.regex.Pattern; @Component public class CustomSanitizer implements SanitizingFunction { // 匹配包含敏感关键词的Key private static final Pattern SENSITIVE_KEY_PATTERN = Pattern.compile(".*(password|secret|token|key)$", Pattern.CASE_INSENSITIVE); @Override public Object apply(Object value, String key) { // 检查Key是否匹配敏感规则 if (key != null && SENSITIVE_KEY_PATTERN.matcher(key).matches()) { return "***"; } // 额外检查值是否包含敏感内容(比如手机号示例) if (value instanceof String strValue) { if (strValue.matches("1[3-9]\\d{9}")) { return "***"; } } return value; } }
以上方案可单独使用,也可组合使用,根据实际需求选择即可。
内容的提问来源于stack exchange,提问作者Ish Mahajan
相关产品推荐
相关产品推荐

