---
title: "Specifying Custom Model Credentials and Service Accounts in ADK"
date: "2026-11-27T08:08:00+07:00"
description: "API keys vs user OAuth vs service accounts, how the Gen AI client picks its credentials, workload identity on Cloud Run, least-privilege IAM roles, per-tenant credential isolation, and keeping secrets out of prompts and code."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-model-credentials-service-accounts.jpg"
alt: "Keyring with access badges arranged in a hierarchy of permission levels"
tags: ['google-adk', 'security', 'authentication', 'service-accounts', 'secrets']
---

Credential choice is the first security decision in an ADK project and the one most often made by accident — whatever was in the tutorial's `.env` file gets promoted to production. The result is predictable: a personal API key in a shared service, a key with owner-level scope, and no way to answer "which identity made this call?" six months later.

This tutorial walks through the credential types available to an ADK agent, how the Gen AI client actually resolves them, how to run on Cloud Run with workload identity instead of keys, and how to isolate credentials per tenant without leaking any of them into the model's context.

## The three credential types, and what each is for

| Credential | Who it is | Scope | Rotate | Use when |
|---|---|---|---|---|
| **API key** | Project, not a person | Project-wide, often broad | Manual, painful | Local development, prototypes |
| **User OAuth (ADC user flow)** | A human | Their IAM permissions | SSO handles it | Interactive dev, acting-as-user debugging |
| **Service account** | A workload | Explicitly granted roles | Automated keys/identity | Production agents |

The rule of thumb: **keys for humans on laptops, service accounts for services in production.** Anything else needs a justification written down.

## How the client resolves credentials

The Gen AI client reads a small set of environment variables and resolves them in order of specificity. On the Gemini Developer API side that means a key:

```bash
export GEMINI_API_KEY='...'      # or GOOGLE_API_KEY (which takes precedence if both are set)
```

On the managed/enterprise backend, no key is involved — the client uses Application Default Credentials plus a project and location:

```bash
export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT='acme-prod'
export GOOGLE_CLOUD_LOCATION='us-central1'
```

```python
from google import genai

client = genai.Client()          # picks up ADC + project/location
# explicit form, when you need it:
client = genai.Client(enterprise=True, project='acme-prod', location='us-central1')
```

**Application Default Credentials** is the mechanism that matters in production: the client looks for credentials in a well-defined order — an explicitly passed credential file, the `GOOGLE_APPLICATION_CREDENTIALS` environment variable, the attached service account of the compute you're running on (Cloud Run, GKE, GCE), then gcloud user credentials. On Cloud Run that chain ends at the runtime service account, which is exactly what you want: **no key files anywhere in the deployment**.

Note that the backend-selection flag has been renamed across SDK generations; set whichever your installed `google-genai` documents rather than copying an old snippet.

## Running on Cloud Run with workload identity

```yaml
# cloud run (conceptual)
service: billing-agent
serviceAccount: billing-agent@acme-prod.iam.gserviceaccount.com
env:
  - name: GOOGLE_CLOUD_PROJECT
    value: acme-prod
  - name: GOOGLE_CLOUD_LOCATION
    value: us-central1
```

Give the runtime service account only what the agent does:

- `roles/aiplatform.user` — model invocation (or the narrower custom role your org requires).
- `roles/datastore.user` — if you use managed search/grounding.
- Read/write on the specific Secret Manager secret and Cloud Storage bucket it owns — granted as `secretmanager.secretAccessor` on *that* secret, not project-wide.

Explicitly **not**: `roles/owner`, `roles/editor`, or a project-wide `iam.serviceAccountKeyAdmin`. If a teammate says "it needs more permissions", make them name the API call that failed.

## Secrets never enter the model's context

The failure mode that actually gets exploited is not a leaked environment variable — it is a secret that reaches the prompt. Sources to block:

1. **Tool returns.** A `get_config()` tool that dumps a dict containing `API_TOKEN` puts the token in the transcript, where it is persisted in session storage, logged, and readable by anyone with session access.
2. **Error messages.** `requests` exceptions and connection strings embed credentials. Sanitize before returning an error to the model (covered in [tool errors](/blog/adk-tool-errors-recoverable-exceptions)).
3. **`ToolContext` misuse.** State is serialized into events and can be inspected; a `temp:` variable holding a bearer token is a bearer token on disk.
4. **Debug logging of requests.** Full request/response logging of a turn that included a secret-bearing tool result.

Patterns that keep secrets out:

- **Fetch credentials inside the tool, at call time**, from a secret manager or a metadata endpoint, use them for the upstream call, and return only the result.
- **Never return raw upstream responses** — return the projection your agent needs.
- **Allowlist tool outputs** by schema rather than filtering for known-bad patterns after the fact.

```python
import google.auth
import google.auth.transport.requests

async def push_order(order_id: str, tool_context) -> dict:
    """Confirm an order with the fulfilment API.

    Args:
        order_id (str): Order identifier.
    """
    creds, _ = google.auth.default(scopes=['...cloud-platform'])
    creds.refresh(google.auth.transport.requests.Request())
    resp = await fulfilment.post(order_id, bearer=creds.token)   # token never leaves this frame
    return {'status': 'success', 'confirmation': resp['confirmation_id']}
```

The token exists for the duration of one HTTP call and appears in no event, no log line, and no prompt.

## Per-tenant credential isolation

Multi-tenant agents often need to act *as the customer* against a customer's API:

- **Hold credentials in a per-tenant store** keyed by tenant ID, never in the agent's prompt or session state.
- **Resolve them inside the tool at call time** from `tool_context.state['tenant_id']`, not from arguments the model supplies. The model choosing which credential to use is a privilege-escalation primitive.
- **Impersonate rather than share.** Where possible, use workload identity federation or service-account impersonation scoped per tenant with a short TTL, instead of storing long-lived tenant keys.
- **Audit per identity.** Log which credential ID (not the credential) was used for each tool call, so an incident can be traced to a tenant action.

## Rotation and hygiene

- Prefer **ambient identity** (workload identity, attached service account) so rotation is automatic.
- Where keys are unavoidable, store them in **Secret Manager**, mount at runtime, and rotate on a schedule with a dual-validity window.
- **Never commit** `.env` files; keep a `*.env.example` with variable names only.
- **Separate projects per environment** — dev keys should not be able to touch production data at all; that's stronger than any IAM rule you'd write inside one project.
- On rotation failure, fail fast with a clear message rather than silently falling back to a cached credential.

## Takeaways

- API keys for local development, attached service accounts (workload identity) for production — no key files in deployments.
- The client resolves credentials from environment + ADC; on Cloud Run the chain ends at the runtime service account, which you scope least-privilege.
- Secrets must never cross into tool results, errors, or state — fetch at call time, return the projection.
- Model-supplied arguments must never select credentials; resolve tenant identity from context you control.
- Rotate automatically where possible, separate environments by project, and log credential IDs for audit.

## Further reading

- [Configuring environment variables and secret handling](/blog/adk-environment-variables-secrets)
- [Tool errors and recoverable exceptions](/blog/adk-tool-errors-recoverable-exceptions)
- [Regional endpoints and residency compliance](/blog/vertex-regional-endpoints-residency-compliance)
- [Preventing SSRF in web-connected agent tools](/blog/ai-security-prompt-injection)
