Spring 以编程方式更改引导应用程序属性加载进程以提高安全性

Spring boot application properties load process change programatically to improve security

我有 spring 启动微服务,其数据库凭据在应用程序属性中定义。

spring.datasource.url=<<url>>
spring.datasource.username=<<username>>
spring.datasource.password=<<password>>

我们不使用 spring 数据源来手动创建连接。仅 Spring 使用 JPA 创建数据库连接。(org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration)

我们只提供应用程序属性,但 spring 会自动创建连接以与数据库连接池一起使用。

我们要求在不使用明文形式的数据库属性的情况下增强安全性。两种可能的方法。

  1. 加密数据库凭据
  2. 使用 AWS 秘密管理器。 (然后通过应用加载获取凭证)

对于选项1,可以使用jasypt,因为我们只是提供属性,不想手动创建数据源,怎么办通过spring框架来理解就是问题所在。如果更好,我可以获得一些工作示例或方法。

关于选项 2,

我需要使用选项 1 和选项 2。提到了每个选项的问题。

您可以为您的属性使用环境变量。您可以像这样使用它们:

spring.datasource.url=${SECRET_URL}

然后您可以检索这些并使用 ProcessBuilder 启动您的 Spring 进程。 (或以任何其他方式设置变量)

我找到了解决问题的方法。

我们需要在spring.factories文件中定义org.springframework.context.ApplicationListener。它应该定义所需的应用程序上下文侦听器,如下所示。

org.springframework.context.ApplicationListener=com.sample.PropsLoader

PropsLoader class 是这样的。

public class PropsLoader implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {


@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

    ConfigurableEnvironment environment = event.getEnvironment();

    String appEnv          = environment.getProperty("application.env");
    //set new properties based on the application environment.  
    // calling other methods and depends on the enviornment and get the required value set  
    Properties props       = new Properties();
    props.put("new_property", "value");

    environment.getPropertySources().addFirst(new PropertiesPropertySource("props", props));

}

}

spring.factories 文件应该在 resources 包和 META-INF 下定义 文件夹。

这将在加载任何其他 bean 之前使用新属性设置应用程序上下文。