在 application.yml 中如果有資料庫連線設定,可能會如下:
上面密碼的部份是用 jasypt 加密,通常不會在設定檔直接寫明碼。那麼,怎麼初始化 jasypt 函式庫呢?
- spring:
- datasource:
- url: jdbc:mysql://127.0.0.1:3306/AUTH
- username: root
- password: ENC(wwCYqJ+PMxrCAY0aPs8v91/oykkFVyux)
- driver-class-name: com.mysql.cj.jdbc.Driver
- jpa:
- database-platform: org.hibernate.dialect.MySQLDialect
- build.gradle
- implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4'
- application.yml
- jasypt:
- encryptor:
- password: ${JASYPT_ENCRYPTOR_PASSWORD}
- algorithm: PBEWithMD5AndDES
- iv-generator-classname: org.jasypt.iv.NoIvGenerator
- @EnableEncryptableProperties
- @EnableEncryptableProperties
- @SpringBootApplication
- public class DemoSecurityApplication {
- public static void main(String[] args) {
- SpringApplication.run(DemoSecurityApplication.class, args);
- }
- }
加入如上 jar 檔。
${JASYPT_ENCRYPTOR_PASSWORD} 會從環境變數取得加解密的 key,要注意最後一行,在 jasypt-spring-boot-starter 2.x 版不需要這個設定,到 3.x 版才需要。
在 @SpringBootApplication 或 @Configuration 所在的 class 上加上 @EnableEncryptableProperties 啟用 jasypt。
沒有留言:
張貼留言