springboot + nacos + aws secretmanager 做账号密码隐私处理

方式一:

java 复制代码
#nacos配置文件

data.yml:
spring:
  cloud:
    nacos:
      discovery:
        ip: ****.com
        port: 80
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://*********/database?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
    hikari:
      idle-timeout: 60000
      connection-timeout: 60000
      validation-timeout: 3000
      login-timeout: 5
      max-lifetime: 60000
      maximum-pool-size: 20

#项目配置文件

bootstrap-test.yml
spring:
  cloud:
    nacos:
      discovery:
        server-addr: http://nacos-headless:8848
      config:
        server-addr: http://nacos-headless:8848
        namespace: TEST
        file-extension: yml
        extension-configs:
          - group: DEFAULT_GROUP
            data-id: global.yml
          - group: common
            data-id: common.yml
          - group: data
            data-id: db.yml
            refresh: true

sm: 
  region: eu-central-1
  doc: dev-fra-as-api-mongodb-user-root-ZMEAVyQppET6GPf
  rdsp: dev-fra-as-api-rds-user-root-xp78N8GvtScLmGn
  rdss: dev-fra-as-pms-rds-v2-readonly-from-sin-user-fra-appplayer-gp3Sex9vbXDU6PL



代码

package com.yuruo.reco.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import com.yuruo.reco.dto.SecretDto;
import com.yuruo.reco.utils.JsonUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;

public class SecretsManagerEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource.getName().contains("[bootstrap-" + environment.getActiveProfiles()[0] + ".yml]")) {
                Region region = Region.of(propertySource.getProperty("sm.region").toString());
                SecretsManagerClient client = SecretsManagerClient.builder().region(region).credentialsProvider(DefaultCredentialsProvider.create()).build();
                // 读取配置
                String primarySecret = getSecretRes(client, propertySource.getProperty("sm.rdsp").toString());
                SecretDto secret = JsonUtils.stringToJavaObject(primarySecret, SecretDto.class);
                Map<String, Object> source = new HashMap<>();
                source.put("spring.datasource.primary.username", secret.getUsername());
                source.put("spring.datasource.primary.password", secret.getPassword());
                String secondarySecret = getSecretRes(client, propertySource.getProperty("sm.rdss").toString());
                secret = JsonUtils.stringToJavaObject(secondarySecret, SecretDto.class);
                source.put("spring.datasource.secondary.username", secret.getUsername());
                source.put("spring.datasource.secondary.password", secret.getPassword());
                String mongosecret = getSecretRes(client, propertySource.getProperty("sm.doc").toString());
                secret = JsonUtils.stringToJavaObject(mongosecret, SecretDto.class);
                source.put("spring.data.mongodb.uri", "mongodb://" + secret.getUsername() + ":" + secret.getPassword()
                        + "@" + secret.getHost() + ":" + secret.getPort());
                propertySources.addLast(new MapPropertySource("secretsManagerPropertySource", source));
            }
        }
    }

    private String getSecretRes(SecretsManagerClient client, String secretName) {
        GetSecretValueRequest request = GetSecretValueRequest.builder().secretId(secretName).build();
        return client.getSecretValue(request).secretString();
    }

}

方式二:

java 复制代码
src/main/resources/META-INF/spring.factories
org.springframework.boot.env.EnvironmentPostProcessor=com.yuruo.reco.config.SecretsManagerEnvironmentPostProcessor


spring:
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect
  cloud:
    nacos:
      discovery:
        ip: ****.com
        port: 80
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://*********/database?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
    username: ${DB_USETRNAME}
    password: ${DB_PASSWORD}
    hikari:
      idle-timeout: 60000
      connection-timeout: 60000
      validation-timeout: 3000
      login-timeout: 5
      max-lifetime: 60000
      maximum-pool-size: 20

package com.yuruo.reco.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;

import com.yuruo.reco.constant.SecretConstant;
import com.yuruo.reco.dto.SecretDto;
import com.yuruo.reco.utils.JsonUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;

public class SecretsManagerEnvironmentPostProcessor implements EnvironmentPostProcessor {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		Region region = Region.of(SecretConstant.SECRET_REGION);
		SecretsManagerClient client = SecretsManagerClient.builder().region(region).credentialsProvider(DefaultCredentialsProvider.create()).build();

		String primarySecret = getSecretRes(client, SecretConstant.SECRET_PRIMARY);
		if(StringUtils.isNotBlank(primarySecret)) {
			SecretDto secret = JsonUtils.stringToJavaObject(primarySecret, SecretDto.class);
			System.setProperty("DB1_USETRNAME", secret.getUsername());
			System.setProperty("DB1_PASSWORD", secret.getPassword());
		}

		String secondarySecret = getSecretRes(client, SecretConstant.SECRET_SECONDARY);
		if(StringUtils.isNotBlank(secondarySecret)) {
			SecretDto secret = JsonUtils.stringToJavaObject(secondarySecret, SecretDto.class);
			System.setProperty("DB2_USETRNAME", secret.getUsername());
			System.setProperty("DB2_PASSWORD", secret.getPassword());
		}

		String mongosecret = getSecretRes(client, SecretConstant.SECRET_MONGO);
		if(StringUtils.isNotBlank(mongosecret)) {
			SecretDto secret = JsonUtils.stringToJavaObject(mongosecret, SecretDto.class);
			System.setProperty("MGDB_URI", "mongodb://"+secret.getUsername()+":"+secret.getPassword()+"@"+ secret.getHost()+":"+secret.getPort()+"/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false");
		}

	}

	private String getSecretRes(SecretsManagerClient client, String secretName) {
		GetSecretValueRequest request = GetSecretValueRequest.builder().secretId(secretName).build();
		return client.getSecretValue(request).secretString();
	}

}
相关推荐
m0_7482350729 分钟前
SpringBoot集成kafka
spring boot·kafka·linq
呜呼~225142 小时前
前后端数据交互
java·vue.js·spring boot·前端框架·intellij-idea·交互·css3
问道飞鱼3 小时前
【Springboot知识】Springboot进阶-实现CAS完整流程
java·spring boot·后端·cas
Q_19284999063 小时前
基于Spring Boot的电影网站系统
java·spring boot·后端
阿moments5 小时前
SpringBoot3-第十篇(整合Web安全)
spring boot·安全·web安全
后端转全栈_小伵5 小时前
SQLite本地数据库的简介和适用场景——集成SpringBoot的图文说明
数据库·spring boot·后端·sqlite·学习方法
李长渊哦6 小时前
使用 Spring Boot 实现文件上传:从配置文件中动态读取上传路径
java·spring boot·spring
猿来入此小猿6 小时前
基于SpringBoot在线音乐系统平台功能实现十七
java·spring boot·后端·毕业设计·音乐系统·音乐平台·毕业源码
繁川6 小时前
Spring Boot缓存预热实战指南
spring boot·spring·缓存
苹果醋37 小时前
Vue3响应式数据: 深入分析Ref与Reactive
java·运维·spring boot·mysql·nginx