整合 Google 登入到 Strapi:在 Kubernetes 上攻克「Secure Cookie over Unencrypted Connection」的心路歷程
前言 在現代 Web 應用開發中,提供第三方登入(Social Login)已經成為標準配備。相比傳統的帳號密碼註冊流程,使用 Google、Facebook、GitHub 等服務登入不僅能降低使用者註冊門檻,還能提升安全性(由大廠處理密碼儲存與驗證)。 當我們決定為 Strapi CMS 後台加入 Google OAuth 登入時,原本以為只是個簡單的設定任務: 在 Google Cloud Console 建立 OAuth 2.0 憑證 在 Strapi 填入 Client ID 和 Client Secret 點擊「Login with Google」按鈕,完成! 但現實總是更複雜。當應用部署到 Kubernetes 叢集後,我們遇到了一個令人困惑的錯誤訊息: Error: Cannot send secure cookie over unencrypted connection 這個錯誤訊息背後,牽涉到 HTTP/HTTPS 協定、Proxy Trust 機制、Kubernetes Ingress 架構、以及瀏覽器 Cookie 安全策略等多層知識。這篇文章將完整記錄我如何一步步拆解問題、理解根本原因、並最終在生產環境中實現安全可靠的 Google 登入功能。 OAuth 2.0 授權碼流程基礎 在深入問題之前,我們先理解 Google OAuth 登入的完整流程。OAuth 2.0 提供了多種授權模式(Grant Types),而 Web 應用最常使用的是「授權碼模式(Authorization Code Flow)」。 sequenceDiagram participant U as 使用者瀏覽器 participant S as Strapi CMS<br/>(你的應用) participant G as Google OAuth Server participant A as Google Authorization Server Note over U,A: 第一階段:取得授權碼 U->>S: 1. 點擊「Login with Google」 S->>U: 2. 重導向到 Google 授權頁 Note right of S: redirect_uri=https://cms.example.com/api/connect/google/callback U->>G: 3. GET /o/oauth2/v2/auth?client_id=...&redirect_uri=... G->>U: 4. 顯示 Google 登入頁面 U->>G: 5. 輸入帳號密碼,同意授權 G->>U: 6. 重導向回應用 (帶著授權碼) Note right of G: https://cms.example.com/api/connect/google/callback?code=AUTH_CODE Note over U,A: 第二階段:用授權碼換取存取權杖 U->>S: 7. GET /api/connect/google/callback?code=AUTH_CODE S->>A: 8. POST /token (帶著 code + client_secret) A->>S: 9. 回傳 access_token + id_token S->>A: 10. 驗證 id_token,取得使用者資料 A->>S: 11. 回傳使用者 email, name 等資訊 Note over U,S: 第三階段:建立 Session (問題發生點!) S->>S: 12. 建立或更新 Strapi 使用者記錄 S->>S: 13. 建立 Session,準備設定 Cookie Note right of S: ⚠️ 這裡檢查連線是否為 HTTPS S->>U: 14. Set-Cookie: strapi_session=...; Secure; HttpOnly U->>S: 15. 後續請求帶著 Cookie 這個流程中有幾個關鍵點: ...