使用具有外部身分的服務帳戶

本文說明如何在使用具有外部身分的 Identity-Aware Proxy (IAP) 時,透過服務帳戶進行驗證。

取得用戶端 ID 和密鑰

  1. 前往 Google Cloud 控制台的「應用程式內購」頁面。

    前往 IAP 頁面

  2. 按一下「應用程式」分頁標籤。

  3. 找出要設定使用服務帳戶的應用程式。

  4. 從溢位選單中選取「前往 OAuth 設定」

畫面上會顯示應用程式的用戶端 ID 和密碼。您需要這些資訊,才能在下一節設定 Identity Platform。

將 Google 設為識別資訊提供者

如果 Identity Platform 專案尚未使用 Google 進行驗證,請使用用戶端 ID 和密碼建立新的設定:

  1. 前往Google Cloud 控制台的「Identity Platform Providers」頁面。
    前往「Identity Providers」(識別資訊提供者) 頁面

  2. 如果您使用的是 Identity Platform 多用戶群架構,請選取與 IAP 資源相關聯的用戶群。

  3. 按一下「新增提供者」

  4. 從供應商清單中選取「Google」Google

  5. 在「Web SDK 設定」下方,輸入您在上一節取得的用戶端 ID 和密鑰。

  6. 按一下 [儲存]

如果您已使用 Google 驗證,可以改用用戶端 ID。這不會影響現有使用者。

  1. 前往Google Cloud 控制台的「Identity Platform Providers」頁面。
    前往「Identity Providers」(識別資訊提供者) 頁面

  2. 如果您使用的是 Identity Platform 多用戶群架構,請選取與 IAP 資源相關聯的用戶群。

  3. 在提供者清單中找出「Google」,然後按一下「編輯」

  4. 按一下「Allowed client IDs」下方的「Add」

  5. 輸入您在上一個部分取得的用戶端 ID。

  6. 按一下 [儲存]

將 Google 權杖換成 Identity Platform 權杖

您首次使用 Google 進行驗證時,Identity Platform 會傳回 Google ID 權杖。接著,您可以呼叫 signInWithIdp,將其換成 Identity Platform 權杖:

Node.js

import * as firebase from 'firebase/app';
import 'firebase/auth';

const config = {
  apiKey: '...',
};
firebase.initializeApp(config);
const cred = firebase.auth.GoogleAuthProvider.credential(google_oidc_id_token);
firebase.auth().signInWithCredential(cred)
  .then((userCredential) => {
    return userCredential.user.getIdToken();
  })
  .then((gcipIdToken) => {
    // This token can now be used to access the resource.
  })
  .catch((error) => {
    // Error occurred.
  });

Python

SIGN_IN_WITH_IDP_API = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp'

def exchange_google_id_token_for_gcip_id_token(api_key, tenant_id, google_open_id_connect_token):
  url = SIGN_IN_WITH_IDP_API + '?key=' + api_key
  data={'requestUri': 'http://localhost',
        'returnSecureToken': True,
        'postBody':'id_token=' + google_open_id_connect_token + '&providerId=google.com',
        'tenantId': tenant_id}
  resp = requests.post(url, data)
  res = resp.json()
  return res['idToken']

REST

要求:

POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=API-KEY

Body:

{
"postBody":"id_token=GOOGLE-ID-TOKEN&providerId=google.com"
"requestUri": "http://localhost",
"returnIdpCredential": true,
"returnSecureToken": true,
"tenantId": "TENANT-ID"
}

將 Identity Platform ID 權杖納入授權標頭,透過 IAP 存取資源:

curl -H "Authorization: Bearer GCIP-ID-TOKEN" "https://example.appspot.com/api"

請注意,外部身分不支援 IAM,因此您必須手動更新應用程式的存取權控管,才能授予服務帳戶存取權。詳情請參閱「外部身分識別碼的 JWT」。