An AI agent that reads a spreadsheet, updates a BigQuery table, or triggers a Cloud Run job needs to prove who it is before Google Cloud lets it do any of that. For a person, proving identity means a login screen. For an agent running unattended, sometimes on a laptop, sometimes inside a container, sometimes on infrastructure that isn't Google Cloud at all, there's no screen and no one around to type a password when a token expires.
Google Cloud already has a mature answer to this problem. It was built for backend services long before agents existed, and most of it applies directly: Application Default Credentials discover the right identity automatically based on where code is running, Workload Identity Federation lets systems outside Google Cloud authenticate without a static key, and service account impersonation hands out short-lived, narrowly scoped tokens instead of long-lived secrets.
The pieces exist. What's less obvious is how to combine them correctly for a system that acts autonomously, chains tool calls together, and processes untrusted input as part of its job.
This guide walks through how Google Cloud authentication for AI agents actually works in practice: how Google Cloud ADC resolves credentials across local, cloud, and hybrid environments, how Workload Identity Federation and service account impersonation remove static keys from the picture, and how to design access that stays least privilege even when the one asking for it is an agent instead of a person.
How Google Cloud Authentication Works for AI Agents Across Local, Cloud, and Hybrid Environments
An AI agent that calls a Google Cloud API is, from Google's point of view, just another caller that needs to prove its identity before every request. What makes agents different from a typical backend service is that they run in more places, act with less direct supervision, and often chain many calls together in a single task.
Google Cloud authentication for AI agents is built on the same primitives used for any workload: OAuth 2.0 access tokens, service accounts, Application Default Credentials for discovery, and Workload Identity Federation for anything running outside Google Cloud.
An agent isn't locked into one method. Its authentication resolves differently depending on where it happens to be running.
Three environments account for most of the pattern differences:
- Local development: The agent runs on a developer's machine, and Google Cloud auth typically falls back to user credentials issued through the Google Cloud CLI, scoped to whatever that developer's own Google Account can access.
- Cloud-native: The agent runs inside Compute Engine, Cloud Run, GKE, or Cloud Functions, and Google Cloud auth resolves an attached service account automatically from the environment's metadata server, with no key files anywhere in the deployment.
- Hybrid or multi-cloud: The agent runs on AWS, Azure, on-premises infrastructure, or inside a third-party runtime, and Google Cloud auth uses Workload Identity Federation to exchange an external identity token for a short-lived Google credential, without ever creating a static key.
The authentication method should follow the deployment target, not the other way around. Hardcoding a service account key into an agent so it "just works everywhere" is exactly the pattern the rest of this guide argues against.
It matters more for agents than for ordinary services, since an agent that acts autonomously, retries failed calls, and processes untrusted input needs a credential surface that stays small and predictable.
Frameworks that connect agents to third-party services increasingly treat this as infrastructure rather than a one-off implementation detail, similar to how an integration layer that handles OAuth, API keys, and bot tokens automatically keeps credential logic consistent across every provider an agent talks to, not just Google Cloud.
Application Default Credentials: Credential Discovery, Precedence, and Deployment Behavior
Application Default Credentials, often shortened to Google Cloud ADC, is the strategy Google's client libraries use to find credentials automatically based on the environment, so the same application code can run in development and production without conditional authentication logic.
Rather than a credential type of its own, ADC is a lookup process, and understanding its precedence matters more than most teams assume.
ADC checks for credentials in this order:
- The
GOOGLE_APPLICATION_CREDENTIALSenvironment variable, which points to a credential file. That file can be a service account key, an external account configuration for Workload Identity Federation or Workforce Identity Federation, or an authorized user file. - A credential file created locally by running the Google Cloud CLI's application default login command, stored at a fixed path that depends on the operating system.
- The attached service account returned by the environment's metadata server, when the code runs on Compute Engine, Cloud Run, GKE, Cloud Functions, or App Engine's flexible environment.
Google's own documentation is explicit that this order is a lookup sequence, not a ranking of trust or preference.
That distinction matters in practice: a stray GOOGLE_APPLICATION_CREDENTIALS variable left behind from local testing will silently take precedence in a production container, causing an agent to authenticate as the wrong identity without any error being thrown.
It's worth explicitly checking for that variable during deployment rather than assuming ADC will resolve to the "obvious" identity.
Deployment behavior follows from this precedence. In local development, ADC usually resolves broad user credentials, often wider in scope than what the agent should have once it's live.
On Compute Engine, Cloud Run, and GKE, ADC resolves the attached service account with no files or environment variables to manage, and Google rotates that credential automatically behind the scenes.
In CI/CD pipelines or on other clouds, ADC resolves through GOOGLE_APPLICATION_CREDENTIALS pointing at a Workload Identity Federation configuration file, which is the pattern covered next.
Workload Identity Federation for Keyless Authentication Across Multi-Cloud and On-Premises Agents
Workload Identity Federation lets Google Cloud trust credentials issued by an external identity provider—AWS, Azure, on-premises Active Directory, or any OpenID Connect or SAML-compliant identity provider—and exchange them for short-lived Google credentials.
No service account key ever needs to be created or stored for this to work.
Two building blocks make it up:
- A workload identity pool, which is a container for external identities.
- A workload identity pool provider, which defines the trust relationship with a specific identity provider through its issuer, audience, and attribute mappings.
From there, teams generally choose between two access patterns:
- Direct resource access: IAM roles are granted straight to the federated principal, so the external identity calls Google Cloud resources under its own identity.
- Service account impersonation: The federated identity is granted the Workload Identity User role and uses it to impersonate a Google service account, inheriting that service account's permissions instead of holding its own broad grants.
Most agent frameworks lean toward the impersonation pattern, since it keeps the permission model centralized on a small number of service accounts rather than sprawling across many external principals.
It is also the pattern with the fewest surprises when a Google Cloud API has limitations around directly federated tokens.
This matters for AI agents specifically because agents frequently run somewhere other than Google Cloud: built on infrastructure from another provider, invoked from inside a CI pipeline, or triggered from a workflow tool that has nothing to do with Google.
Workload Identity Federation removes the temptation to paste a downloaded JSON key into a config file, where it would sit valid indefinitely until someone remembered to rotate it. External tokens exchanged through federation typically live minutes to hours instead.
Google Kubernetes Engine has its own variant of this pattern, Workload Identity Federation for GKE, which is covered in more detail in the containers section below.
Service Account Impersonation and Short-Lived Credentials for Safer Agent Access
Service account impersonation lets one identity—a person, a CI system, or another service account—request a temporary credential for a target service account without ever holding that target account's long-lived key.
It's the mechanism underneath both Workload Identity Federation and a lot of everyday local development.
The mechanics are straightforward: the calling identity needs the Service Account Token Creator role on the target service account, then calls the IAM Service Account Credentials API's generateAccessToken method to receive a working OAuth 2.0 access token.
A few details are worth knowing:
- Lifetime: Tokens default to 3,600 seconds, or one hour, and can be extended up to 43,200 seconds, or twelve hours, for workloads that genuinely need a longer window.
- No refresh token: Unlike a typical OAuth flow, an expired impersonated token can't be refreshed. The caller has to repeat the impersonation request. That's a deliberate design choice: it forces every credential to be reissued against current IAM policy instead of persisting unchecked.
- Delegation chains: Impersonation can be chained across multiple service accounts, where each hop needs the Token Creator role granted on the account ahead of it. This is useful for separating an agent's everyday identity from a higher-privilege identity it's only occasionally allowed to assume.
For an agent, this means its baseline identity can stay low privilege for routine tool calls, and step up to a more privileged service account only for specific, auditable operations.
Each impersonation call shows up as its own entry in Cloud Audit Logs tied to both identities involved, which is a far clearer trail than a single static credential reused for everything an agent does.
Most agent frameworks need an equivalent pattern for every provider they connect to, not only Google Cloud: somewhere to store the specific credentials each integration requires without handing them to the agent directly, which is close to how a dedicated integration layer keeps plugin credentials scoped and rotated behind the API surface an agent actually calls.
Designing Least Privilege and Zero Trust Access for Autonomous AI Agents
Least privilege is harder to enforce for agents than for people, since agents don't usually request access when they hit something new. They just attempt the call.
That means overprovisioning tends to stay invisible until something goes wrong.
A few approaches hold up well in practice:
- Split service accounts by capability, not by agent: Separate identities for read-heavy work, such as querying BigQuery or reading from Cloud Storage, from anything that writes, mutates, or deletes, so a compromised read-only path can't escalate into a write path.
- Use IAM Conditions to narrow access further: Time-bound bindings, resource-tag-based bindings, or request attribute checks can scope a role tighter than the role definition alone would allow.
- Prefer custom roles over broad predefined roles for agent service accounts: An agent rarely needs Editor or Owner. It needs the three or four permissions its specific tool calls actually use.
- Treat any agent action beyond a simple read as something that deserves a policy check: A valid token should not automatically mean unrestricted execution.
Zero trust, applied to agents, means not trusting an identity just because it authenticated successfully.
What it's asking to do still needs to be checked against policy at call time, which is the real difference between "can this identity obtain a token" and "should this identity be allowed to run this specific action right now."
One pattern worth building in directly is a human approval step for sensitive or destructive calls, where the agent's request is queued for a person to approve or deny before it executes, rather than relying on authentication alone as the only gate.
This is the same reasoning behind letting teams gate sensitive actions behind human approval before they execute for any connected integration, not just Google Cloud resources.
Securing Agent Credentials Against Prompt Injection, Token Theft, and Credential Exfiltration
Agents carry a risk that ordinary backend services don't: their inputs—a document they read, a page they fetch, an email they process—can contain instructions crafted to make the agent take an action it shouldn't, including leaking its own credentials.
A few concrete risks are worth naming directly:
-
Prompt injection: An attacker convinces an agent to print its own environment variables or configuration. If
GOOGLE_APPLICATION_CREDENTIALSpoints at a key file, that file's contents can end up in an agent's output or in a log a bad actor later reads. - Token theft through logs or traces: Access tokens, even short-lived ones, can end up captured by verbose debug logging, observability tooling, or crash reports. If the token is still valid when it's read, it can be replayed.
- Credential exfiltration through chained tool calls: An agent tricked into passing a token or key as a parameter to an external tool can leak it straight outside the intended trust boundary.
The mitigations aren't prompt-level fixes. They're architectural.
Avoiding long-lived keys in the first place, through ADC, Workload Identity Federation, and impersonation, means there's nothing durable to steal, and a leaked short-lived token has a far smaller blast radius since it expires within the hour.
Credential resolution should also sit outside the agent's own reasoning loop entirely. The code path that fetches and applies a token shouldn't be something the agent's generated output can influence, which is an architecture decision more than a prompting one.
Tokens should be scoped tightly per call rather than reused broadly across a session, and Cloud Audit Logs are worth monitoring specifically for unusual impersonation events, since that audit trail is something a short-lived token gives you that a static key never does.
This is also the reasoning behind keeping raw credentials out of an agent's context entirely: an integration layer that resolves credentials at call time so an agent only ever sees method names and results is a more defensible boundary than trusting the agent to handle a token responsibly, which is the same principle behind a hosted relay that stores none of your credentials in the first place.
Choosing the Right Authentication Pattern for Containers, Kubernetes, and Air-Gapped Systems
The right pattern depends heavily on where the agent's runtime actually sits:
- Containers on Compute Engine or Cloud Run: ADC resolves the attached service account automatically from the metadata server. This is the simplest case. Nothing needs to be explicitly configured inside the container image itself.
- GKE: Use Workload Identity Federation for GKE rather than mounting service account key files as Kubernetes secrets. It binds a Kubernetes ServiceAccount to a Google identity so a pod authenticates automatically, and on Autopilot clusters it's enabled by default.
- Self-managed Kubernetes outside Google Cloud, on-premises, or on another provider: Use Workload Identity Federation with the cluster's own OIDC issuer as the identity provider. This is the same underlying pattern used for AWS or Azure, just pointed at the cluster's own token issuer.
- Air-gapped or fully disconnected systems: This is the honest edge case. Workload Identity Federation and impersonation both depend on reaching Google's token exchange and IAM Credentials endpoints over the network, so an agent with no outbound connectivity to Google Cloud can't use either.
For air-gapped systems, options narrow to private connectivity, a VPN or Interconnect combined with Private Google Access, so the disconnected network can still reach Google's APIs privately, or accepting that a fully offline agent needs a proxy or relay component with real connectivity to broker those calls on its behalf.
The practical way to decide is to sort by connectivity first, privilege second.
If the runtime can reach Google Cloud's APIs at all, prefer ADC with an attached service account, or Workload Identity Federation, over anything involving a static key.
If it genuinely can't reach them, a relay or gateway component becomes necessary, and that component now holds the credential the agent doesn't, which deserves its own security review.
Google Cloud gives AI agents a strong foundation for identity, but most agents don't only talk to Google Cloud. They also need Slack, Notion, GitHub, Stripe, and dozens of other services, each with its own auth quirks and token lifecycles.
Corsair is an open-source integration layer built for exactly this problem: it handles OAuth, API keys, and credential rotation across hundreds of plugins so agents authenticate consistently everywhere, not only inside Google Cloud.
Teams can self-host it for free or run it through Corsair's hosted Hub, which never stores customer credentials. The same principles that apply to designing least-privilege, short-lived access for Google Cloud apply to every other integration an agent touches too.
Frequently Asked Questions
What is the difference between Application Default Credentials and a service account key?
ADC is a discovery strategy that looks for credentials in a fixed order: an environment variable, a local credential file from the Google Cloud CLI, or the attached service account from the metadata server. It isn't a credential type by itself.
A service account key is one specific, long-lived credential type that ADC can pick up if GOOGLE_APPLICATION_CREDENTIALS points at it. Google recommends avoiding key files where possible, since an attached service account or Workload Identity Federation can usually provide the same access without a static file to protect.
Do AI agents need Workload Identity Federation if they already run inside Google Cloud?
Not for the parts of an agent that run natively on Compute Engine, Cloud Run, or GKE, since ADC already resolves the attached service account automatically there.
Workload Identity Federation becomes relevant the moment part of the agent's workflow runs outside Google Cloud, such as a CI pipeline, another cloud provider, or an on-premises system that still needs to call a Google Cloud API.
How long do impersonated service account credentials last?
By default, an access token generated through service account impersonation lasts 3,600 seconds, or one hour, and can be configured up to 43,200 seconds, or twelve hours, for workloads that need a longer window.
There's no refresh token involved. Once it expires, the caller has to request a new one, which keeps every credential reissued against current IAM policy rather than persisting unchecked.
Can an AI agent be tricked into leaking its own Google Cloud credentials through prompt injection?
It's a real risk if the agent's runtime holds a long-lived key and its reasoning loop has any path to reading environment variables, configuration files, or verbose logs.
The fix isn't a prompt-level patch. It's architectural: keep credential resolution in trusted application code outside the agent's context, and prefer short-lived tokens over static keys so even a successful leak has a small, time-limited blast radius.
What's the simplest way to authenticate an AI agent running in a container on Google Cloud?
If the container runs on Compute Engine, Cloud Run, or GKE, attach a dedicated service account with only the permissions the agent needs and let ADC resolve it automatically from the metadata server, with no key files or environment variables to manage.
On GKE specifically, use Workload Identity Federation for GKE to bind the pod's Kubernetes ServiceAccount to that Google identity.
Top comments (0)