Jasypt安全框架提供了Spring的集成,主要是實現
PlaceholderConfigurerSupport類或者其子類。
在Sring 3.1之後,則推薦使用PropertySourcesPlaceholderConfigurer類作爲屬性替換配置類,這裏Spring集成Jasypt則使用Jasypt對屬性替換配置類的實現。EncryptablePropertySourcesPlaceholderConfigurer。
在Spring中集成比較容易,而且Jasypt官方也給出了配置Bean的方式和使用Jasypt標籤的XML方式,而Spring boot集成就稍微有點不一樣,需要創建一個自動配置類,並且創建一個注入PlaceholderConfigurerSupport的jasypt實現了的Bean .
下面是一個使用示例:
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.spring31.properties.EncryptablePropertySourcesPlaceholderConfigurer; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.Ordered; import org.springframework.core.io.ClassPathResource; /** * Author : secondriver * Date : 2016/5/26 */ @Configuration @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) public class EncryptPropertyPlaceholderAutoConfiguration { private static final String SECURITY_PROPERTIES_FILE = "security.properties"; @Bean @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM); encryptor.setPassword("security"); EncryptablePropertySourcesPlaceholderConfigurer configurer = new EncryptablePropertySourcesPlaceholderConfigurer(encryptor); configurer.setLocation(new ClassPathResource(SECURITY_PROPERTIES_FILE)); return configurer; } }
配置文件的寫入和Spring XML的基本類似。application.yml相當於applicationContext.xml,security.properties就是要進行屬性替換的配置文件。
application.yml:
spring: datasource: url: jdbc:mysql://localhost:3306/abc?useSSL=false username: root password: ${jdbc.password}
security.properties:
jdbc.password=ENC(jWgGELCkuxRuCI2Aqa6cF9VCxYpuKEZr)
創建數據源的時候在使用屬性參數時,會對ENC()中的內容進行解密,達到認證成功,創建數據源完成。