赞
踩
Springboot整合Jasypt,实现配置信息的安全,如数据库连接.账号和密码.接口凭证信息等。
Jasypt可以为Springboot加密的信息很多,主要有:
以下3种方法:
如果你的Spring Boot
项目使用@SpringBootApplication
或@EnableAutoConfiguration
注解,在pom中加入以下starter jar依赖。
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
如果你不使用@SpringBootApplication
或@EnableAutoConfiguration
两个自动配置注解的话,可以添加如下依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.3</version>
</dependency>
然后在配置Java类中使用注解@EncryptablePropertySource
. 举例:
@Configuration
@EnableEncryptableProperties
public class MyApplication {
...
}
即可对整个Spring的环境的配置信息进行加密解密 (包括:System Property 系统变量、Envirnment Property 环境变量、Command Line argument 命令行参数、Application.properties 应用配置文件、Yaml properties 应用配置文件、other custom property sources 其它配置文件)
如果你不使用@SpringBootApplication
或@EnableAutoConfiguration
两个自动配置注解,又不想对整个spring环境的参数进行加密解密的话,这里有第3种方法. 首先,在你的工程中添加如下依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.3</version>
</dependency>
然后,在Java配置类中添加@EncryptablePropertySource
注解. 类似于添加spring的@PropertySource
注解. 比如:
@Configuration
@EncryptablePropertySource(name="EncryptedProperties", value="classpath:encrypted.properties")
public class MyApplication {
...
}
非常方便的是,一个Java类中可以添加一个@EncryptablePropertySources
注解,也可以添加一组@EncryptablePropertySources
注解,就像这样:
@Configuration
@EncryptablePropertySources({
@EncryptablePropertySource("classpath:encrypted.properties"),@EncryptablePropertySource("classpath:encrypted2.properties")})
public class MyApplication {
...
}
另外,需要注意的是从1.8版本开始,@EncryptablePropertySource
支持YAML文件.
从版本1.15开始,支持使用第4种方法启用加密属性. 自定义一个ConfigurableEnvironment
类,比如:EncryptableEnvironment
、StandardEncryptableEnvironment
、StandardEncryptableServletEnvironment
,与SpringApplicationBuilder
类一起使用,以这种方式自定义使用环境:
new SpringApplicationBuilder()
.environment(new StandardEncryptableEnvironment())
.sources(YourApplicationClass.class).run(args);
这个方法只需要使用jasypt-spring-boot
的依赖. 不需要starter jar
依赖项. 这种方法对于在启动过程中访问加密属性非常有用. 虽然在大多数场景中不是必需的,但在定制Spring Boot
的初始化行为或整合某些初始化配置的功能时可能很有用(如日志配置)。举个具体的例子,在logback-spring.xml
文件中,我们如果要对springProperty
标签的属性启用加密,这是唯一一种方法。例如:
<springProperty name="user" source="db.user"/>
<springProperty name="password" source="db.password"/>
<appender name="db" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource
class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<driverClass>org.postgresql.Driver</driverClass>
<url>jdbc:postgresql://localhost:5432/simple</url>
<user>${user}</user>
<password>${password}</password>
</connectionSource>
</appender>
使用这种机制可以用来初始化需要传递敏感凭证的数据库日志记录Appender(Database Logging Appender)。另外,我们需要提供一个自定义的StringEncryptor
,以及一个静态构建器方法StandardEncryptableEnvironment#builder
来进行操作:
StandardEncryptableEnvironment
.builder()
.encryptor(new MyEncryptor<
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。