【发布时间】:2019-09-23 14:03:09
【问题描述】:
我们混合了一些尚未迁移到 spring-boot 或 spring cloud 的遗留 spring 应用程序以及 spring boot 应用程序。我正在创建一个 Spring 组件,如果属性值已加密并具有前缀,则该组件将在加载环境时自动解密 spring 属性。属性可以在 .properties 文件中(用于旧版应用程序)或 .yaml 文件中(较新的 Spring Boot 应用程序)。
无论来源如何,组件都应该能够解密任何 spring 属性,并且应该可以与任何 spring 版本一起使用,并且不依赖于 spring boot。组件还应该透明地解密属性。它应该从属性文件中读取密码,因此需要在开头加载密码文件。
我们有自己的 ecrypt/decrypt,不想使用 jaspyt。
到目前为止尝试过的事情:
我喜欢 this 创建 ApplicationListener 的方法,但这与 spring boot(ApplicationEnvironmentPreparedEvent) 相关。对于像 ContextRefreshed 或 ContextStart 这样的 Spring 事件,我看不到如何获得 ConfigurableApplicationContext/ConfigurableEnvironment。有人在没有 spring boot/cloud 的情况下创建了用于加密/解密的侦听器吗?
我还创建了一个自定义 ApplicationContextInitializer,并将其添加到 web.xml 的上下文参数中,但这似乎不起作用。当我调试它时,我认为它不会从我的 app.properties 文件中加载/读取属性。
@Component
public class DecryptingPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize( ConfigurableApplicationContext applicationContext ) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
for ( PropertySource<?> propertySource : environment.getPropertySources() ) {
Map<String, Object> propertyOverrides = new LinkedHashMap<>();
decodePasswords( propertySource, propertyOverrides );
if ( !propertyOverrides.isEmpty() ) {
PropertySource<?> decodedProperties = new MapPropertySource( "decoded " + propertySource.getName(),
propertyOverrides );
environment.getPropertySources().addBefore( propertySource.getName(), decodedProperties );
}
}
}
private void decodePasswords(PropertySource<?> source, Map<String, Object> propertyOverrides) {
if ( source instanceof EnumerablePropertySource ) {
EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) source;
for ( String key : enumerablePropertySource.getPropertyNames() ) {
Object rawValue = source.getProperty( key );
if ( rawValue instanceof String ) {
//decrypt logic here
propertyOverrides.put( key, decryptedValue );
}
}
}
}
}
是否有人必须做类似的事情或有更好的想法?有没有办法我可以监听应用程序事件然后处理? 感谢您的帮助
【问题讨论】:
-
你可以写一个自定义的SPEL函数来解密。
-
您可以尝试 AOP 并将其配置为在每次调用
Proprties.load()时运行 -
@Ivan 有没有办法可以监听应用程序事件然后进行处理?
-
@AkshayKhopka 谢谢。就像在一个应用程序中事件然后处理?
标签: java spring spring-boot encryption properties