Nacos Config 配置帐号密码加密后,注入过程中如何解密?

背景

线上项目规定不能在配置文件中出现帐号、密码的明文信息,所以必须加密。

引入 Nacos Config 配置后,Nacos Config 帐号密码、加密,服务注册发现也用相同的 nacos 帐号密码,那么如何解密才能保证 Nacos Config 服务能够正确启动呢?

本文记录这个问题的解决思路。

解决方案

首先,跟踪 Nacos Config 的启动流程,关键配置信息是 NacosConfigProperties 这个类控制的,所以需要让它能加载到解密的信息,才能保证配置管理服务启动成功。

其次,它在 spring.cloud.nacos.config 下面没有配置帐号密码时,会从环境变量中加载信息。 第三,服务注册发现配置属性 NacosDiscoveryPropertiesspring.cloud.nacos.discovery 未配置帐号密码的情况下,也会从环境变量中获取 nacos 全局的帐号和密码。 第四个技术点,可以通过 environment.getPropertySources() 对象操作系统环境变量,并对环境变量进行修改。

所以解决步骤是:

  1. 在 bootstrap.yml 配置的 spring.cloud.nacos.config 下面配置 Nacos 帐号密码,且加密。
typescript 复制代码
    nacos:
      # nacos 服务器地址
      server-addr: xxx:8848
      # nacos 配置中心,Nacos 帐号、密码
      config:
        enabled: true
        username: 对称加密结果
        password: 对称加密结果
  1. 自定义一个 org.springframework.cloud.bootstrap.BootstrapConfiguration 类,并在 spring.factories 中添加声明。
typescript 复制代码
org.springframework.cloud.bootstrap.BootstrapConfiguration=\xxx.MyBootStrapConfiguration
  1. MyBootStrapConfiguration 的构造函数中,对加密的 nacos 帐号密码进行解密,并回写到四个环境变量中。
java 复制代码
String username = environment.getProperty("spring.cloud.nacos.config.username");
String password = environment.getProperty("spring.cloud.nacos.config.password");

// TODO 解密

// 解密结果存储到新的配置集合
Map<String, Object> newConfigMap = new HashMap<>();
newConfigMap.put("spring.cloud.nacos.config.username", username);
newConfigMap.put("spring.cloud.nacos.config.password", password);

// 更新 nacos.username/password 用于服务发现配置         
newConfigMap.put("spring.cloud.nacos.username", username);
newConfigMap.put("spring.cloud.nacos.password", password);

// 这里将加密配置加载到配置列表的第一个位置,优先级最高;类型为 MapPropertySource,name 名称随意。
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addFirst(new MapPropertySource("myConfig", newConfigMap));

注意事项:

  1. @ConfigurationProperties("spring.cloud.nacos.discovery") NacosDiscoveryProperties 这个配置类会监控配置变化,但是它的配置信息直接从 yml 中加载的,如果帐号密码直接配置后,就不会从 Environment 对象中加载了,所以不能配置 nacos.discovery.username/password 属性。
  2. BootstrapConfiguration 级别的类,框架内置了 NacosConfigBootstrapConfiguration ,这个类引用了 nacos.config 配置对应的属性类 NacosConfigProperties ,所以自定义的启动类的优先级必须比内置的 NacosConfigBootstrapConfiguration 高,使用 @Order 属性设置最高优先级,在真正的 Nacos 服务类启动之前对帐号密码的环境变量进行偷梁换柱。

自定义的 Bootstrap 启动配置类,完整配置如下:

typescript 复制代码
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyBootStrapConfiguration {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 依赖系统配置环境变量,需要偷梁换柱,解密掉加密配置
     */
    @Autowired
    private ConfigurableEnvironment environment;

    @PostConstruct
    public void decryptNacosConfig() {
		 String username = environment.getProperty("spring.cloud.nacos.config.username");
		  String password = environment.getProperty("spring.cloud.nacos.config.password");
		
		// TODO 解密
		
		// 解密结果存储到新的配置集合
		Map<String, Object> newConfigMap = new HashMap<>();
		newConfigMap.put("spring.cloud.nacos.config.username", username);
		newConfigMap.put("spring.cloud.nacos.config.password", password);
		
		// 更新 nacos.username/password 用于服务发现配置         
		newConfigMap.put("spring.cloud.nacos.username", username);
		newConfigMap.put("spring.cloud.nacos.password", password);
		
		// 这里将加密配置加载到配置列表的第一个位置,优先级最高;类型为 MapPropertySource,name 名称随意。
		MutablePropertySources propertySources = environment.getPropertySources();
		propertySources.addFirst(new MapPropertySource("myConfig", newConfigMap));
    }
}

延伸思考知识

typescript 复制代码
public NacosConfigProperties nacosConfigProperties(ApplicationContext context) {
		if (context.getParent() != null
				&& BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
						context.getParent(), NacosConfigProperties.class).length > 0) {
			return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
					NacosConfigProperties.class);
		}
		return new NacosConfigProperties();
	}

跟踪过程中发现 MutablePropertySources 有很多不同类型的属性资源,这些配置的区别是什么?

启示录

typescript 复制代码
@AutoConfigureBefore(NacosConfigBootstrapConfiguration.class)
无效

这个对于需要注册 org.springframework.cloud.bootstrap.BootstrapConfiguration 这种类型的自动注入类来说,是无效的。

有效的方式是通过 @Order(Ordered.HIGHEST_PRECEDENCE) 提升它的优先级。

参考资料

  1. 《Spring Cloud Context: Application Context Services》
  2. 《SpringBoot通过 EnvironmentPostProcessor 对配置文件解密》
  3. 《Nacos 服务注册与发现关键类》
  4. 《Alibaba-Nacos-Discovery 源码分析》
相关推荐
天天摸鱼的java工程师23 分钟前
Redis 集群缓存不一致?这篇把坑给你挖明白了
后端
天天摸鱼的java工程师25 分钟前
Redis 除了做缓存还能干什么?
后端
AntBlack34 分钟前
Trae Agent :能提高开发效率的功能都值亲自体验一下
后端·ai编程·trae
江梦寻2 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
风象南2 小时前
SpringBoot的4种死信队列处理方式
java·spring boot·后端
互联网全栈架构3 小时前
遨游Spring AI:第一盘菜Hello World
java·人工智能·后端·spring
coderSong25688 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
Mr_Air_Boy9 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
咖啡啡不加糖10 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
大鸡腿同学11 小时前
纳瓦尔宝典
后端