將配置文件中的機密資訊與一般配置分離
1. 建一個不進版本控制的 application-secrets.yml
application-secrets.yml
google:
client-id: amnTLEmgeOsaiYn963G95375680435-u6j4tf7j
client-secret: 37569GERMKWE5375680435-u6j48035-u6jG4WJTcO-lOf
2. 使用 Spring Profiles
在 application.yml 中:
spring:
profiles:
include: secrets # 自動包含 secrets 這個 profile 的內容
security:
oauth2:
client:
registration:
google:
client-id: ${google.client-id}
client-secret: ${google.client-secret}
scope:
- openid
- email
- profile
這樣 Spring 啟動時會同時加載 application.yml 和 application-secrets.yml,變數 ${google.client-id} 就能被正確解析。
防啟動失敗註記
spring:
profiles:
include: secrets # 自動包含 secrets 這個 profile 的內容
security:
oauth2:
client:
registration:
google:
client-id: ${google.client-id:NEED_TO_SET_CLIENT_ID}
client-secret: ${google.client-secret:NEED_TO_SET_CLIENT_SECRET}
scope:
- openid
- email
- profile
-
沒有預設值:
client-id: ${google.client-id}$\rightarrow$ 找不到變數 $\rightarrow$ 啟動掛掉。 -
有預設值:
client-id: ${google.client-id:MISSING}$\rightarrow$ 找不到變數 $\rightarrow$ 正常啟動,但功能無效。
看到的 Client ID 是 NEED_TO_SET_CLIENT_ID,方便確認是application-secrets.yml 沒有被正確讀取到,而不是去懷疑 Google 的伺服器掛了或是網路有問題。
3. 極度重要的安全提醒 .gitignore
為了安全,請務必確認你的專案根目錄下的 .gitignore 檔案中有包含這行:
如果不加這行,你執行 git push 時,你的 Google Secret 就會直接送到 GitHub 上公開了。