【问题标题】:Externalize password in Spring Boot properties file在 Spring Boot 属性文件中外部化密码
【发布时间】:2020-01-27 08:44:43
【问题描述】:

我有 application.properties 文件

spring.profiles.active=local

我有 application-local.properties,它有很多领域,包括

api.password = password123

如您所见,我在属性文件中有硬编码密码 123。

假设我在 windows 上,并且我在 windows 上有 app.properties 文件

 api.password = password123

我想通过app.properties读取spring boot属性文件中的api.password

我怎样才能实现它?

【问题讨论】:

  • 区别在哪里?仅仅通过添加第二个文件不会获得更多的安全性
  • 您只想读取该属性吗?还是 app.properties 文件中的所有属性?
  • 也许你可以把密码放在你的环境变量中
  • @Marged 我不会成为我的 GIT HUB 的 app.properties 它会在每个环境的 Linux 机器上,即 DEV、UAT 和 PROD
  • 我建议仅在 application.yml 中保留属性,但是当您启动应用程序时,您可以从命令行输入密码,例如 java -jar -Dapi.password=mysecretpassword myApp.jar(您也可以创建 bat /.sh 文件),但仅在命令行上使用它将确保密码不在机器上

标签: spring-boot


【解决方案1】:

启动参数

如果您想从非标准位置读取属性,您可以使用--spring.config.location--spring.config.additional-location 参数启动您的应用程序。

$ java -jar app.jar --spring.config.location=file:./app.properties

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

@PropertySource

如果不控制启动参数,可以使用@PropertySource注解。 只需注释您的主类(或任何其他配置):

 @PropertySource("file:.app.properties")

您可以设置ignoreResourceNotFound=true,这样即使文件不存在,应用程序也会启动。

https://docs.spring.io/spring/docs/5.1.9.RELEASE/javadoc-api/org/springframework/context/annotation/PropertySource.html

阅读文档

实际上有 17 种方法将属性传递给 Spring-Boot 应用程序。

我建议你熟悉一下约定,因为了解哪个文件优先是至关重要的:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config

【讨论】:

    【解决方案2】:

    也许你可以像下面这样使用 --spring.config.location

    $ java -jar myApp.jar --spring.config.location=file:/directoryof file/app.properties

    【讨论】:

    • 如果你确定只有然后回答。你的技术不会;行不通
    • 这样可以加载属性文件吗?
    • 如果你想读出你的类路径,这是唯一的方法。当您使用配置文件时,您必须使用 $ java -jar myApp.jar --spring.config.name=app --spring.config.location=file:/propertfilefoldername
    • @OracleMonkey 它有效,你应该尊重人们试图帮助你
    【解决方案3】:

    我使用了 jasypt:https://github.com/ulisesbocchio/jasypt-spring-boot 加密密码,然后你提供一个解密字符串(jasypt.encryptor.password)作为启动参数。这样配置和 git-repos 上就没有 useabel 密码.....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-21
      • 2020-07-30
      • 2015-06-26
      • 2020-07-25
      • 2021-05-17
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多