Repository Public
1---2title: Use WIF with Google Cloud3url: https://platform.claude.com/docs/en/manage-claude/wif-providers/gcp4description: Federate Google Cloud workloads (Cloud Run, Cloud Functions, App Engine, GCE, GKE) to the Claude API using Google-signed identity tokens instead of static API keys.5---67Any Google Cloud compute environment with access to the instance metadata server (Cloud Run, Cloud Functions, App Engine, Compute Engine (GCE), and GKE with Workload Identity) can request a Google-signed identity token for its attached service account. The token's issuer is `https://accounts.google.com`, and Anthropic can validate it directly through standard OIDC discovery, with no extra Google Cloud configuration required.89This guide shows how to register the Google issuer with Anthropic, bind a Google service account to an Anthropic service account, and have your workload exchange its identity token for a short-lived Claude API access token.1011## Prerequisites1213* Familiarity with [WIF concepts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#concepts): service accounts, federation issuers, and federation rules.14* A Google Cloud project with a workload running on Cloud Run, Cloud Functions, App Engine, Compute Engine, or GKE.15* A user-managed Google service account attached to that workload (not the Compute Engine default service account).16* Permission to create service accounts, federation issuers, and federation rules in the Claude Console for your Anthropic organization.1718## Configure Google Cloud1920Google issues identity tokens automatically to any workload with an attached service account. There is nothing to enable on the Google side beyond attaching the right service account, but the steps differ slightly between standard compute and GKE.2122<Tabs>23 <Tab title="Cloud Run, Cloud Functions, App Engine, GCE">24 Attach a dedicated service account to your service or instance:2526 ```bash CLI27 gcloud run deploy my-service \28 --service-account inference-worker@my-project.iam.gserviceaccount.com29 ```3031 Inside the workload, the metadata server returns a signed identity token on demand. Request it with the `audience` you intend to register on the Anthropic side, and include `format=full` so the response carries the `email` claim:3233 ```text wrap34 GET http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full35 Metadata-Flavor: Google36 ```3738 Or, with the gcloud CLI:3940 ```bash CLI41 gcloud auth print-identity-token \42 --audiences="https://api.anthropic.com" \43 --include-email44 ```4546 The SDK equivalents are shown in [Acquire and use the token](https://platform.claude.com/docs/en/manage-claude/wif-providers/gcp#acquire-and-use-the-token).4748 The decoded token payload looks like this:4950 ```json51 {52 "iss": "https://accounts.google.com",53 "aud": "https://api.anthropic.com",54 "sub": "104892...",55 "azp": "104892...",56 "email": "inference-worker@my-project.iam.gserviceaccount.com",57 "email_verified": true,58 "exp": 177552712059 }60 ```6162 The `sub` claim is the Google service account's opaque numeric unique ID. The `email` claim is the human-readable service account address. Match on both `sub` and `email` in your federation rule.63 </Tab>6465 <Tab title="GKE with Workload Identity">66 Enable [Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) on your cluster and bind your Kubernetes service account to a Google service account with the `iam.gke.io/gcp-service-account` annotation:6768 ```yaml69 apiVersion: v170 kind: ServiceAccount71 metadata:72 name: inference-worker73 namespace: prod74 annotations:75 iam.gke.io/gcp-service-account: inference-worker@my-project.iam.gserviceaccount.com76 ```7778 With this binding in place, the GKE metadata server returns a Google-signed token identical to the Cloud Run and GCE case: same `https://accounts.google.com` issuer, same `email` claim, same fetch URL. Configure Anthropic exactly as in the next section.7980 A `format=full` token from GKE additionally includes `google.compute_engine.project_id`, `google.compute_engine.zone`, and `google.compute_engine.instance_name` claims, which you can reference in a federation rule's `condition` matcher (a CEL expression like `claims.google.compute_engine.project_id == "my-project"`) to scope access to a specific cluster or node pool.8182 <Note>83 If you do not want to bind Kubernetes service accounts to Google service accounts, GKE pods can instead use the cluster's own OIDC issuer (`https://container.googleapis.com/v1/projects/PROJECT/locations/REGION/clusters/CLUSTER`) with a projected `serviceAccountToken` volume. That path uses a per-cluster issuer rather than `accounts.google.com`. See [Use WIF with Kubernetes](https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes) for that pattern.84 </Note>85 </Tab>86</Tabs>8788## Configure Anthropic8990In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **Google Cloud** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.9192The wizard creates these resources for you. Use the following values whether you enter them in the wizard or send them to the [Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api):9394**Federation issuer:** Google publishes its OIDC discovery document publicly, so use discovery mode. This single issuer covers every Google Cloud surface (Cloud Run, GCE, Cloud Functions, App Engine, and GKE with Workload Identity). Differentiate workloads with rules, not issuers.9596```json97{98 "name": "gcp",99 "issuer_url": "https://accounts.google.com",100 "jwks": { "type": "discovery" }101}102```103104**Federation rule:** Match on both the `sub` and `email` claims. `email` is the readable service-account address; `sub` is the service account's numeric unique ID, which Google never reuses, so pinning it protects the rule if the service account is deleted and a new one is later created with the same email. Find the unique ID with `gcloud iam service-accounts describe SA_EMAIL --format='value(uniqueId)'`.105106```json107{108 "name": "gcp-inference-worker",109 "issuer_id": "fdis_...",110 "match": {111 "audience": "https://api.anthropic.com",112 "claims": {113 "sub": "104892101234567890123",114 "email": "inference-worker@my-project.iam.gserviceaccount.com"115 }116 },117 "target": {118 "type": "service_account",119 "service_account_id": "svac_..."120 },121 "workspace_id": "wrkspc_...",122 "oauth_scope": "workspace:developer",123 "token_lifetime_seconds": 600124}125```126127## Acquire and use the token128129Inside your Google Cloud workload, fetch the identity token from the metadata server, exchange it at `POST /v1/oauth/token`, and use the returned bearer token to call the Claude API. Each Anthropic SDK handles the exchange and refresh loop for you when you supply a token-provider callable that returns a fresh identity token from the metadata server, as shown in the following examples.130131<CodeGroup>132 ```bash cURL133 # Fetch the Google-signed identity token from the metadata server134 JWT=$(curl -sS -H "Metadata-Flavor: Google" \135 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full")136137 # Exchange it for an Anthropic access token138 RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \139 -H "content-type: application/json" \140 --data @- <<JSON141 {142 "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",143 "assertion": "$JWT",144 "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",145 "organization_id": "$ANTHROPIC_ORGANIZATION_ID",146 "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",147 "workspace_id": "$ANTHROPIC_WORKSPACE_ID"148 }149 JSON150 )151 ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)152153 # Call the Claude API154 curl -sS https://api.anthropic.com/v1/messages \155 -H "authorization: Bearer $ACCESS_TOKEN" \156 -H "anthropic-version: 2023-06-01" \157 -H "content-type: application/json" \158 -d '{159 "model": "claude-opus-5",160 "max_tokens": 1024,161 "messages": [{"role": "user", "content": "Hello from Cloud Run"}]162 }' | jq -r '.content[] | select(.type == "text") | .text'163 ```164165 ```python Python166 import os167 import anthropic168 import google.auth.transport.requests169 import google.oauth2.id_token170 from anthropic import WorkloadIdentityCredentials171172 AUDIENCE = "https://api.anthropic.com"173174175 def fetch_google_identity_token() -> str:176 request = google.auth.transport.requests.Request()177 return google.oauth2.id_token.fetch_id_token(request, AUDIENCE)178179180 client = anthropic.Anthropic(181 credentials=WorkloadIdentityCredentials(182 identity_token_provider=fetch_google_identity_token,183 federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],184 organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],185 service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],186 workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),187 ),188 )189190 message = client.messages.create(191 model="claude-opus-5",192 max_tokens=1024,193 messages=[{"role": "user", "content": "Hello from Cloud Run"}],194 )195 print(next(block.text for block in message.content if block.type == "text"))196 ```197198 ```typescript TypeScript199 import Anthropic from "@anthropic-ai/sdk";200 import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";201202 const METADATA_URL =203 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full";204205 async function fetchGoogleIdentityToken(): Promise<string> {206 const response = await fetch(METADATA_URL, {207 headers: { "Metadata-Flavor": "Google" }208 });209 return response.text();210 }211212 const client = new Anthropic({213 credentials: oidcFederationProvider({214 identityTokenProvider: fetchGoogleIdentityToken,215 federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,216 organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,217 serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,218 workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,219 baseURL: "https://api.anthropic.com",220 fetch221 })222 });223224 const message = await client.messages.create({225 model: "claude-opus-5",226 max_tokens: 1024,227 messages: [{ role: "user", content: "Hello from Cloud Run" }]228 });229 for (const block of message.content) {230 if (block.type === "text") {231 console.log(block.text);232 }233 }234 ```235236 ```go Go237 const audience = "https://api.anthropic.com"238239 googleIDToken := func(ctx context.Context) (string, error) {240 creds, err := idtoken.NewCredentials(&idtoken.Options{Audience: audience})241 if err != nil {242 return "", err243 }244 tok, err := creds.Token(ctx)245 if err != nil {246 return "", err247 }248 return tok.Value, nil249 }250251 client := anthropic.NewClient(252 option.WithFederationTokenProvider(googleIDToken, option.FederationOptions{253 FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),254 OrganizationID: os.Getenv("ANTHROPIC_ORGANIZATION_ID"),255 ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),256 WorkspaceID: os.Getenv("ANTHROPIC_WORKSPACE_ID"),257 }),258 )259260 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{261 Model: anthropic.ModelClaudeOpus5,262 MaxTokens: 1024,263 Messages: []anthropic.MessageParam{264 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from Cloud Run")),265 },266 })267 if err != nil {268 panic(err)269 }270 for _, block := range message.Content {271 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {272 fmt.Println(textBlock.Text)273 break274 }275 }276 ```277278 ```java Java279 HttpClient http = HttpClient.newHttpClient();280 HttpRequest metadataRequest = HttpRequest.newBuilder()281 .uri(URI.create("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full"))282 .header("Metadata-Flavor", "Google")283 .build();284285 IdentityTokenProvider fetchGoogleIdentityToken = () -> {286 try {287 return http.send(metadataRequest, HttpResponse.BodyHandlers.ofString()).body();288 } catch (Exception e) {289 throw new RuntimeException(e);290 }291 };292293 AnthropicClient client = AnthropicOkHttpClient.builder()294 .federationTokenProvider(295 fetchGoogleIdentityToken,296 System.getenv("ANTHROPIC_FEDERATION_RULE_ID"),297 System.getenv("ANTHROPIC_ORGANIZATION_ID"),298 System.getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"))299 .build();300301 var message = client.messages().create(MessageCreateParams.builder()302 .model(Model.CLAUDE_OPUS_5)303 .maxTokens(1024)304 .addUserMessage("Hello from Cloud Run")305 .build());306307 IO.println(message.content());308 ```309310 ```csharp C#311 using Anthropic.Credentials;312 // ...313314 var credentials = new WorkloadIdentityCredentials(new WorkloadIdentityOptions315 {316 FederationRuleId = Environment.GetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID")!,317 OrganizationId = Environment.GetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID"),318 ServiceAccountId = Environment.GetEnvironmentVariable("ANTHROPIC_SERVICE_ACCOUNT_ID"),319 WorkspaceId = Environment.GetEnvironmentVariable("ANTHROPIC_WORKSPACE_ID"),320 IdentityTokenProvider = new MetadataTokenProvider(),321 });322 using var client = new AnthropicClient(new ClientOptions { Credentials = credentials });323324 var message = await client.Messages.Create(new()325 {326 Model = Model.ClaudeOpus5,327 MaxTokens = 1024,328 Messages = [new() { Role = Role.User, Content = "Hello from Cloud Run" }],329 });330 foreach (var block in message.Content)331 {332 if (block.Value is TextBlock textBlock)333 {334 Console.WriteLine(textBlock.Text);335 }336 }337338 class MetadataTokenProvider : IIdentityTokenProvider339 {340 private const string METADATA_URL =341 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full";342343 private static readonly HttpClient httpClient = new()344 {345 DefaultRequestHeaders = { { "Metadata-Flavor", "Google" } },346 };347348 public async Task<string> GetIdentityTokenAsync(CancellationToken ct = default)349 {350 return await httpClient.GetStringAsync(METADATA_URL, ct);351 }352 }353 ```354355 ```bash CLI356 # Write the Google-signed identity token to a file the CLI can read357 ANTHROPIC_IDENTITY_TOKEN_FILE=$(mktemp)358 curl -sS -H "Metadata-Flavor: Google" \359 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full" \360 > "$ANTHROPIC_IDENTITY_TOKEN_FILE"361 export ANTHROPIC_IDENTITY_TOKEN_FILE362363 # ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID, and364 # ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID are read from the environment.365 ant messages create \366 --model claude-opus-5 \367 --max-tokens 1024 \368 --message '{role: user, content: "Hello from Cloud Run"}'369 ```370371 ```php PHP372 use Anthropic\Client;373 use Anthropic\Credentials\WorkloadIdentityCredentials;374375 const METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full';376377 $context = stream_context_create([378 'http' => ['header' => "Metadata-Flavor: Google\r\n"],379 ]);380381 $credentials = new WorkloadIdentityCredentials(382 identityTokenProvider: fn() => file_get_contents(METADATA_URL, false, $context),383 federationRuleId: getenv('ANTHROPIC_FEDERATION_RULE_ID'),384 organizationId: getenv('ANTHROPIC_ORGANIZATION_ID'),385 serviceAccountId: getenv('ANTHROPIC_SERVICE_ACCOUNT_ID'),386 workspaceId: getenv('ANTHROPIC_WORKSPACE_ID') ?: null,387 );388 $client = new Client(credentials: $credentials);389390 $message = $client->messages->create(391 model: 'claude-opus-5',392 maxTokens: 1024,393 messages: [['role' => 'user', 'content' => 'Hello from Cloud Run']],394 );395 $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');396 echo $textBlock->text, PHP_EOL;397 ```398399 ```ruby Ruby400 require "anthropic"401 require "net/http"402403 METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full"404405 credentials = Anthropic::WorkloadIdentityCredentials.new(406 identity_token_provider: -> { Net::HTTP.get(URI(METADATA_URL), {"Metadata-Flavor" => "Google"}) },407 federation_rule_id: ENV.fetch("ANTHROPIC_FEDERATION_RULE_ID"),408 organization_id: ENV.fetch("ANTHROPIC_ORGANIZATION_ID"),409 service_account_id: ENV.fetch("ANTHROPIC_SERVICE_ACCOUNT_ID"),410 workspace_id: ENV["ANTHROPIC_WORKSPACE_ID"]411 )412 client = Anthropic::Client.new(credentials: credentials)413414 message = client.messages.create(415 model: "claude-opus-5",416 max_tokens: 1024,417 messages: [{role: "user", content: "Hello from Cloud Run"}]418 )419 puts message.content.find { it.type == :text }.text420 ```421</CodeGroup>422423Google identity tokens expire after roughly one hour. The SDKs re-invoke the token provider and re-exchange automatically before expiry. For shell scripts that run longer than the access token's `expires_in`, refresh on a timer and repeat the exchange.424425## Verify the setup426427From inside your workload, decode the identity token and confirm the claims match your rule:428429```bash cURL430curl -sS -H "Metadata-Flavor: Google" \431 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.anthropic.com&format=full" \432 | jq -rR 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson'433```434435Check that `iss` is `https://accounts.google.com`, `aud` is `https://api.anthropic.com`, and `email` matches the value in your federation rule. Then run the exchange from the previous section. A successful exchange returns an `access_token` beginning with `sk-ant-oat01-` and an `expires_in` value in seconds. If the exchange fails with the opaque `401` `authentication_error` response (message `Authentication failed`), check the [authentication history page](https://platform.claude.com/settings/workload-identity-federation?tab=history) for the deny reason and see [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange); the most common Google Cloud-side cause is the `email` claim missing (request the token with `format=full` so it is included).436437## Scope your rule438439<Warning>440 The Google `sub` claim is the service account's opaque numeric unique ID and has no stable prefix. A `subject_prefix` with a trailing `*` matches arbitrary service accounts across every Google Cloud project, and any of them could obtain a federated Anthropic token.441</Warning>442443Lock the rule's `match` block to the narrowest scope that fits your use case:444445* **Match `sub` exactly:** Set the full numeric unique ID in `claims.sub` and never use `subject_prefix` for Google tokens.446* **Pin the `email` claim:** Add `claims.email` alongside `sub` so both the stable ID and the readable address must match.447* **Pin the audience:** Set `audience` to the exact value you request from the metadata server so tokens minted for other consumers are rejected.448* **Pin the project on GKE:** For `format=full` tokens, add a `condition` such as `claims.google.compute_engine.project_id == "my-project"` to restrict the rule to one project's nodes.449450## Next steps451452* Read the [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) page for the full resource model and SDK credential precedence.453* Add a separate federation rule per environment (production, staging) so you can revoke one without affecting the others.454