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

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

取得用戶端 ID 和密鑰

  1. 前往 Google Cloud 控制台的「IAP」(身分識別感知存取權) 頁面。

    前往 IAP 頁面

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

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

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

系統會顯示應用程式的用戶端 ID 和密鑰。您會在下一節設定 Identity Platform 時需要用到這些資訊。

將 Google 設定為識別資訊提供者

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

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

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

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

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

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

  6. 按一下 [儲存]

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

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

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

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

  4. 在「允許的用戶端 ID」下方,按一下「新增」

  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

內文:

{
"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」。