我的任务是在配置文件中混淆密码 . 虽然我不认为这是正确的方法,但经理不同意......
所以我正在开发的项目基于Spring Boot,我们正在使用YAML配置文件 . 目前密码是纯文本的:
spring:
datasource:
url: jdbc:sqlserver://DatabaseServer
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: ele
password: NotTheRealPassword
我们的想法是使用一些支持模糊或加密密码的特殊语法:
spring:
datasource:
url: jdbc:sqlserver://DatabaseServer
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: ele
password: password(Tm90VGhlUmVhbFBhc3N3b3Jk)
为了使其工作,我想使用正则表达式解析属性值,如果匹配,则将值替换为deobfuscated / decrypted值 .
But how do I intercept the property value?
4 回答
如果最终得到这个工作 . (主要感谢stephane-deraco,github)
解决方案的关键是实现
ApplicationContextInitializer<ConfigurableApplicationContext>
的类 . 我叫它PropertyPasswordDecodingContextInitializer
.主要问题是让 Spring 天使用这个
ApplicationContextInitializer
. 重要信息可在reference中找到 . 我选择使用META-INF / spring.factories的方法,内容如下:PropertyPasswordDecodingContextInitializer
使用PropertyPasswordDecoder
和一个实现类,目前为简单起见Base64PropertyPasswordDecoder
.PropertyPasswordDecodingContextInitializer.java
PropertyPasswordDecoder.java
Base64PropertyPasswordDecoder.java
请注意,ApplicationContext尚未在此阶段完成初始化,因此自动装配或任何其他与bean相关的机制将无法正常工作 .
Update: 包括@ jny的建议 .
只需使用https://github.com/ulisesbocchio/jasypt-spring-boot,开箱即用
我使用@ Daniele Torino的答案并进行了一些小改动 .
首先,由于他链接到如何使 spring 识别初始化程序的选项,我选择在_1047128中执行:
其次,IDEA告诉我,
else if (source instanceof CompositePropertySource) {
是多余的,因为CompositePropertySource
继承自EnumerablePropertySource
.第三,我相信有一个小错误:它弄乱了 property 解决的顺序 . 如果在环境中有一个编码属性,而在
application.properties
文件中有另一个,则环境值将被application.properties
值覆盖 . 我改变了逻辑,在编码之前插入decodeProperties:Inspired by @gogstad. Here is my major action in the spring boot project to encrypted my username and password and decrypted them in the project to work with tomcat:
1. In pom.xml file
2. In App.java (注意:要在tomcat上部署解密的springboot,你应该添加@ServletComponentScan注释并扩展SpringBootServletInitializer)
3. Encrypted your username and password and fill the application.properties file with the result:
输出就像下面的演示:
4. under the directory src/main/resources/config add two properties file: