google-cloud-recipe-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Authenticating to Google Cloud

Google Cloud认证

Authentication is the process of proving who you are. In Google Cloud, you represent a Principal (an identity like a user or a service). This is the first step before Authorization (determining what you can do).
Authentication 是证明你是谁的过程。在Google Cloud中,你代表一个主体(如用户或服务之类的身份)。这是授权(确定你能做什么)之前的第一步。

Authentication

认证

Clarifying Questions for the Agent

向Agent确认的问题

Before providing a specific solution, clarify the following with the user:
  1. Who or what is authenticating? (A human developer, a local script, or an application running in production?)
  2. Where is the code running? (Local laptop, Compute Engine, GKE, Cloud Run, or another cloud like AWS/Azure?)
  3. What is the target? (A Google Cloud API like Storage/BigQuery, or a custom application you built?)
  4. Are you using a high-level client library? (e.g., Python, Go, Node.js libraries usually handle ADC automatically.)

在提供具体解决方案前,请与用户确认以下内容:
  1. 谁或什么进行认证?(人类开发者、本地脚本,还是运行在生产环境中的应用?)
  2. 代码运行在何处?(本地笔记本电脑、Compute EngineGKECloud Run,还是AWS/Azure等其他云平台?)
  3. 目标是什么?(Google Cloud API如Storage/BigQuery,还是你构建的自定义应用?)
  4. 是否使用高级客户端库?(例如Python、Go、Node.js库通常会自动处理ADC。)

Human Authentication

人类用户认证

For users to access Google Cloud, they need an identity that Google Cloud can recognize.
用户要访问Google Cloud,需要拥有Google Cloud可识别的身份。

Types of User Identities

用户身份类型

Google Cloud supports several ways to configure identities for your internal workforce (developers, administrators, employees):
  • Google-Managed Accounts: You can use Cloud Identity or Google Workspace to create managed user accounts. These are called managed accounts because your organization controls their lifecycle and configuration.
  • Federation using Cloud Identity or Google Workspace: You can federate identities to allow users to use their existing identity and credentials to sign in to Google services. Users authenticate against an external identity provider (IdP), but you must keep accounts synchronized into Google Cloud using tools like Google Cloud Directory Sync (GCDS) or an external authoritative source like Active Directory or Microsoft Entra ID.
  • Workforce Identity Federation: This lets you use an external IdP to authenticate and authorize a workforce using IAM directly. Unlike standard federation, you do not need to synchronize user identities from your existing IdP to Google Cloud identities. It supports syncless, attribute-based single sign-on.
Google Cloud支持多种为内部员工(开发者、管理员、雇员)配置身份的方式:
  • Google托管账号:你可以使用Cloud Identity或Google Workspace创建托管用户账号。这些账号被称为托管账号,因为你的组织可以控制它们的生命周期和配置。
  • 使用Cloud Identity或Google Workspace进行联邦认证:你可以通过联邦身份让用户使用现有身份和凭据登录Google服务。用户通过外部身份提供商(IdP)进行认证,但你必须使用Google Cloud Directory Sync (GCDS)或Active Directory、Microsoft Entra ID等外部权威源将账号同步到Google Cloud。
  • 员工身份联邦:这允许你使用外部IdP直接通过IAM对员工进行认证和授权。与标准联邦不同,你无需将现有IdP中的用户身份同步到Google Cloud身份。它支持无同步、基于属性的单点登录。

Methods of Access for Developers and Administrators

开发者与管理员的访问方式

Used for interacting with Google Cloud resources and APIs during development and management.
  • Google Cloud Console: The primary web interface. You authenticate using your Google Account (Gmail or Google Workspace).
  • gcloud CLI (
    gcloud auth login
    )
    : Used to authenticate the CLI itself so you can run management commands (e.g.,
    gcloud compute instances list
    ). It uses a Credential (like an OAuth 2.0 refresh token) stored locally.
  • Local Development with App Default Credentials (ADC) (
    gcloud auth application-default login
    )
    : This is different from CLI auth. It creates a local JSON file that Google Cloud Client Libraries (Python, Java, etc.) use to act as "you" when you run code on your laptop.
  • Service Account Impersonation: For security reasons, developers should avoid downloading Service Account keys entirely. Instead, they should authenticate as humans (
    gcloud auth login
    ) and use Service Account Impersonation to run CLI commands or generate short-lived credentials. This is a critical best practice for local development and troubleshooting.
用于在开发和管理期间与Google Cloud资源及API交互。
  • Google Cloud控制台:主要的Web界面。你可以使用Google账号(Gmail或Google Workspace)进行认证。
  • gcloud CLI
    gcloud auth login
    :用于认证CLI本身,以便你可以运行管理命令(例如
    gcloud compute instances list
    )。它使用存储在本地的凭据(如OAuth 2.0刷新令牌)。
  • 使用Application Default Credentials (ADC)进行本地开发(
    gcloud auth application-default login
    :这与CLI认证不同。它会创建一个本地JSON文件,Google Cloud客户端库(Python、Java等)在你笔记本电脑上运行代码时会用它来代表“你”。
  • 服务账号模拟:出于安全考虑,开发者应完全避免下载服务账号密钥。相反,他们应以人类身份认证(
    gcloud auth login
    ),并使用服务账号模拟来运行CLI命令或生成短期凭据。这是本地开发和故障排查的关键最佳实践。

For End-Users and Customers

终端用户与客户

Used when a human (who is not a developer) needs to access a web application you've deployed on Google Cloud. Note: These are distinct from workforce identities.
  • Identity-Aware Proxy (IAP): Acts as a central authorization layer for web applications. It intercepts web requests and verifies the user's identity (via Google Workspace, Cloud Identity, or external providers) before letting them reach the application. It's often used to protect internal apps without a VPN, or secure customer portals.
  • Identity Platform: A Customer Identity and Access Management (CIAM) solution for adding consumer sign-in (email/password, phone, social) directly into the code of your custom-built applications.

当人类(非开发者)需要访问你部署在Google Cloud上的Web应用时使用。注意:这些身份与员工身份不同。
  • Identity-Aware Proxy (IAP):作为Web应用的集中授权层。它拦截Web请求,在用户访问应用前验证其身份(通过Google Workspace、Cloud Identity或外部提供商)。它常被用于无需VPN即可保护内部应用,或安全保护客户门户。
  • Identity Platform:一款客户身份与访问管理(CIAM)解决方案,用于直接在你自定义构建的应用代码中添加消费者登录功能(邮箱/密码、手机号、社交账号)。

Service-to-Service Authentication

服务间认证

When code runs in production, it should use a Service Account rather than a human user account.
当代码在生产环境中运行时,应使用服务账号而非人类用户账号。

Service Accounts and Service Agents

服务账号与服务代理

  • Service Account: A special identity intended for non-human users. It's like a "robot identity" with its own email address.
  • Service Agent: A service account managed by Google that allows a service (like Pub/Sub) to access your resources on your behalf.
  • 服务账号:一种专为非人类用户设计的特殊身份。它就像一个带有自己邮箱地址的“机器人身份”。
  • 服务代理:由Google管理的服务账号,允许某服务(如Pub/Sub)代表你访问你的资源。

Best Practice: Attaching Service Accounts

最佳实践:挂载服务账号

Instead of using Service Account Keys (dangerous JSON files), you should attach a custom service account to the Google Cloud resource. The resource's environment then provides a Token (a short-lived digital object) via a local metadata server.
  • Compute Engine: Assign a service account during VM creation.
  • Cloud Run: Assign a service account in the service configuration.
不要使用服务账号密钥(危险的JSON文件),而是应该将自定义服务账号挂载到Google Cloud资源上。资源环境随后会通过本地元数据服务器提供一个令牌(一种短期数字对象)。

Special Cases & Advanced Topics

特殊场景与高级主题

Kubernetes Engine (GKE)

Kubernetes Engine (GKE)

Use Workload Identity Federation for GKE to map Kubernetes identities to IAM principal identifiers. This grants specific Kubernetes workloads access to specific Google Cloud APIs. Learn more here.
使用**GKE工作负载身份联邦**将Kubernetes身份映射到IAM主体标识符。这允许特定的Kubernetes工作负载访问特定的Google Cloud API。点击了解更多

External Workloads (Workload Identity Federation)

外部工作负载(工作负载身份联邦

For code running outside Google Cloud (e.g., AWS, Azure, or on-prem), do not use keys. Instead, use Workload Identity Federation to exchange an external token (like an AWS IAM role) for a short-lived Google Cloud access token.
对于运行在Google Cloud外部的代码(例如AWS、Azure或本地环境),不要使用密钥。相反,使用工作负载身份联邦将外部令牌(如AWS IAM角色)交换为短期Google Cloud访问令牌。
API keys are encrypted strings used for public data (e.g., Google Maps) or simplified access like Vertex AI Express Mode, which allows fast testing of Gemini models without complex setup. Both humans and services (e.g., Cloud Run-based AI agent) can use API keys, for the services that support it.
Note: API keys should be restricted to specific APIs and projects to minimize security risks. Store API keys in a secrets manager like Secret Manager to prevent accidental exposure.
API密钥是加密字符串,用于公共数据(如Google Maps)或简化访问,例如**Vertex AI快速模式**,它允许无需复杂设置即可快速测试Gemini模型。人类和服务(例如基于Cloud Run的AI agent)都可以使用API密钥,前提是服务支持该方式。
注意:应限制API密钥仅用于特定API和项目,以最小化安全风险。将API密钥存储在Secret Manager等密钥管理器中,防止意外泄露。

OAuth 2.0 Access Scopes

OAuth 2.0访问范围

While IAM is the modern way to handle authorization, legacy Compute Engine VMs and GKE node pools still rely on Access Scopes alongside IAM. If a VM's scope is restricted, the attached service account will fail to make API calls even if it has the correct IAM permissions. Check this first if attached service accounts are failing unexpectedly.
虽然IAM是处理授权的现代方式,但旧版Compute Engine VM和GKE节点池仍然依赖访问范围和IAM。如果VM的范围受到限制,即使挂载的服务账号拥有正确的IAM权限,也无法成功调用API。如果挂载的服务账号意外失败,请首先检查这一点。

Short-Lived Credentials

短期凭据

The underlying mechanism for impersonation and secure service-to-service communication is the IAM Service Account Credentials API. This API generates short-lived access tokens, OpenID Connect (OIDC) ID tokens, or self-signed JSON Web Tokens (JWTs) dynamically, removing the need for static credentials.

模拟和安全服务间通信的底层机制是IAM服务账号凭据API。该API动态生成短期访问令牌、OpenID Connect (OIDC) ID令牌或自签名JSON Web令牌(JWT),无需静态凭据。

Authorization

授权

After Authentication, Google Cloud uses Identity and Access Management (IAM) to determine what the authenticated principal can do.
  • Allow Policy: A record that binds a Principal to a Role on a Resource.
  • Predefined Roles: Prebuilt roles like
    roles/storage.objectViewer
    or
    roles/bigquery.dataEditor
    . Always try to use these first.
  • Custom Roles: User-defined collections of specific permissions if predefined roles are too broad.

认证完成后,Google Cloud使用**身份与访问管理(IAM)**来确定已认证主体可以执行的操作。
  • 允许策略:将主体角色绑定到资源的记录。
  • 预定义角色:预构建的角色,如
    roles/storage.objectViewer
    roles/bigquery.dataEditor
    请优先使用这些角色。
  • 自定义角色:如果预定义角色权限过宽,用户可以定义包含特定权限的自定义角色集合。

Examples

示例

Human-to-Service (Local Python Development)

人类到服务(本地Python开发)

  1. Authn: Run
    gcloud auth application-default login
    to create local credentials (ADC).
  2. Authz: Grant your email the
    roles/storage.objectViewer
    role on a bucket.
  3. Code: Use the Python
    storage.Client()
    . It automatically finds your local credentials via ADC. Note: ADC searches in a specific order—first checking the
    GOOGLE_APPLICATION_CREDENTIALS
    environment variable, then the local gcloud JSON file, and finally the attached service account metadata server.
  1. 认证:运行
    gcloud auth application-default login
    创建本地凭据(ADC)。
  2. 授权:为你的邮箱授予存储桶的
    roles/storage.objectViewer
    角色。
  3. 代码:使用Python
    storage.Client()
    。它会通过ADC自动找到你的本地凭据。注意:ADC会按特定顺序搜索——首先检查
    GOOGLE_APPLICATION_CREDENTIALS
    环境变量,然后是本地gcloud JSON文件,最后是挂载的服务账号元数据服务器。

Service-to-Service (Cloud Run to Cloud SQL)

服务到服务(Cloud Run到Cloud SQL)

  1. Authn: Attach a custom Service Account to your Cloud Run service.
  2. Authz: Grant that Service Account the
    roles/cloudsql.client
    role on the project.
  3. Code: The Cloud Run environment provides the token automatically to the connection driver.
  1. 认证:将自定义服务账号挂载到你的Cloud Run服务。
  2. 授权:为该服务账号授予项目的
    roles/cloudsql.client
    角色。
  3. 代码:Cloud Run环境会自动将令牌提供给连接驱动。

Calling a Custom Application (OIDC)

调用自定义应用(OIDC

When calling a private Cloud Run service from another service, the caller generates a Google-signed OpenID Connect (OIDC) ID Token and passes it in the
Authorization: Bearer <TOKEN>
header.

当从另一个服务调用私有Cloud Run服务时,调用方会生成Google签名的OpenID Connect (OIDC) ID令牌,并将其放在
Authorization: Bearer <TOKEN>
请求头中传递。

Validation Checklist

验证清单

  • Is the user running code locally? Suggest
    gcloud auth application-default login
    or Service Account Impersonation.
  • Is the user attempting to use Service Account keys locally? Strongly discourage this and recommend impersonation.
  • Is the user running in production? Recommend attaching a custom, least-privilege service account, NOT using keys.
  • Is the user relying on the Compute Engine Default Service Account? Recommend creating a custom service account instead.
  • Is the user running on another cloud? Recommend Workload Identity Federation.
  • Is the user calling a custom app? Recommend OIDC ID Tokens.
  • Has the user restricted their API Keys? Check for appropriate API Key Restrictions.
  • 用户是否在本地运行代码?建议使用
    gcloud auth application-default login
    服务账号模拟
  • 用户是否尝试在本地使用服务账号密钥?强烈不建议这样做,推荐使用模拟方式。
  • 用户是否在生产环境运行?建议挂载自定义、最小权限的服务账号,不要使用密钥
  • 用户是否依赖Compute Engine默认服务账号?建议创建自定义服务账号替代。
  • 用户是否在其他云平台运行?推荐使用工作负载身份联邦。
  • 用户是否调用自定义应用?推荐使用OIDC ID令牌。
  • 用户是否限制了API密钥?检查是否设置了适当的API密钥限制

References

参考资料