在本機開發環境中,您可以向 ADC 提供使用者憑證或服務帳戶憑證。
使用者憑證
如果您在本機開發環境 (例如開發工作站) 中執行程式碼,最佳做法是使用與使用者帳戶相關聯的憑證。
透過使用者帳戶設定 ADC 的方式,取決於您的使用者帳戶是由 Google 管理 (也就是 Google 帳戶),還是由其他識別資訊提供者 (IdP) 管理,以及使用者帳戶是否已與員工身分聯盟連結。Google 帳戶
如要使用 Google 帳戶設定 ADC,請使用 Google Cloud CLI:
-
安裝 Google Cloud CLI。
如果您使用外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
登入畫面會隨即顯示。登入後,您的憑證會儲存在 ADC 使用的本機憑證檔案中。
外部 IdP
如要為由外部 IdP 管理並與員工身分聯盟連結的使用者帳戶設定 ADC,請按照下列步驟操作:
-
安裝 Google Cloud CLI。 安裝完成後,執行下列指令來初始化 Google Cloud CLI:
gcloud init如果您使用外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
登入畫面會隨即顯示。登入後,您的憑證會儲存在 ADC 使用的本機憑證檔案中。
透過使用者憑證設定 ADC 的訣竅
透過使用者帳戶設定 ADC 時,請注意下列事項:
如果 ADC 是以使用者帳戶設定,可能需要完成額外的設定步驟,才能搭配某些 API 使用。假如看到錯誤訊息,指出 API 未在專案中啟用,或是沒有可用的配額專案,請參閱「使用者憑證無法運作」一節。
本機 ADC 檔案包含更新權杖。任何有權存取檔案系統的使用者,都能使用該檔案取得有效的存取權杖。如果不再需要這些本機憑證,可以使用
gcloud auth application-default revoke指令撤銷憑證。本機 ADC 檔案與使用者帳戶相關聯,而非 gcloud CLI 設定。變更其他 gcloud CLI 設定可能會改變 gcloud CLI 使用的身分,但不會影響本機 ADC 檔案或 ADC 設定。
服務帳戶憑證
您可以透過服務帳戶模擬功能或服務帳戶金鑰,使用服務帳戶的憑證設定 ADC。
服務帳戶模擬
您可以使用服務帳戶模擬功能設定本機應用程式預設憑證 (ADC) 檔案。支援模擬功能的用戶端程式庫可以自動使用這些憑證。使用模擬功能建立的本機 ADC 檔案支援下列語言:
- C#
- Go
- Java
- Node.js
- Python
針對模擬的服務帳戶,您必須擁有服務帳戶權杖建立者 (roles/iam.serviceAccountTokenCreator) IAM 角色。詳情請參閱「必要的角色」一節。
使用服務帳戶模擬功能建立本機 ADC 檔案:
gcloud auth application-default login --impersonate-service-account SERVICE_ACCT_EMAIL
您現在可以使用支援語言的用戶端程式庫,方式與設定本機 ADC 檔案並提供使用者憑證後相同。驗證程式庫會自動尋找憑證。詳情請參閱「進行驗證以使用用戶端程式庫」一文。
並非所有驗證程式庫都支援使用服務帳戶模擬功能產生的本機 ADC 檔案憑證。詳情請參閱這篇文章。
服務帳戶金鑰
如果無法透過使用者帳戶或服務帳戶模擬功能進行本機開發,可以使用服務帳戶金鑰。
如要建立服務帳戶金鑰並提供給 ADC 使用,請按照下列步驟操作:
- 按照「建立服務帳戶金鑰」一節中的只是,建立具有應用程式所需角色的服務帳戶,以及該服務帳戶的金鑰。
-
Set the environment variable
GOOGLE_APPLICATION_CREDENTIALSto the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again.
後續步驟
瞭解使用服務帳戶金鑰的最佳做法。
進一步瞭解 ADC 如何尋找憑證。
瞭解驗證方式。