使用具有外部身份的服务账号

本文介绍使用 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 提供方页面。
    转到“身份提供商”页面

  2. 如果您使用的是 Identity Platform 多租户,请选择与您的 IAP 资源关联的租户。

  3. 点击添加提供商

  4. 从提供商列表中选择 Google

  5. Web SDK 配置下,输入您在上一节中获取的客户端 ID 和密码。

  6. 点击保存

如果您已经在使用 Google 身份验证,则可以改用客户端 ID。这不会影响您的现有用户。

  1. 转到 Google Cloud 控制台中的 Identity Platform 提供方页面。
    转到“身份提供商”页面

  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