您可以在本機開發環境中,為 ADC 提供使用者憑證或服務帳戶憑證。
使用者憑證
如果程式碼是在本機開發環境 (例如開發工作站) 中執行,最佳做法是使用與使用者帳戶相關聯的憑證。
您如何設定 ADC 與使用者帳戶,取決於您的使用者帳戶是由 Google 管理 (也就是 Google 帳戶),還是由其他身分識別資訊提供者 (IdP) 管理,以及是否使用Workforce Identity Federation 進行聯盟。
使用 Google 帳戶設定 ADC
如要使用 Google 帳戶設定 ADC,請使用 Google Cloud CLI:
-
After installing the Google Cloud CLI, initialize it by running the following command:
gcloud init
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
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.
標記指定範圍。--scopes
系統隨即會顯示登入畫面。登入後,憑證會儲存在 ADC 使用的本機憑證檔案中。
使用由外部 IdP 管理的帳戶設定 ADC
如要為由外部 IdP 管理且與員工身分聯盟建立關聯的使用者帳戶設定 ADC,請按照下列步驟操作:
-
After installing the Google Cloud CLI, initialize it by running the following command:
gcloud init
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
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_CREDENTIALS
to 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 如何尋找憑證。
- 驗證 Cloud 用戶端程式庫。
- 驗證 REST 使用權限。
- 探索驗證方法。