SPB Git

Repository Public

github-actions.md 14.1 KB 335 lines markdown

1---2title: Use WIF with GitHub Actions3url: https://platform.claude.com/docs/en/manage-claude/wif-providers/github-actions4description: Authenticate GitHub Actions workflows to the Claude API with short-lived identity tokens instead of long-lived API keys.5---67Every GitHub Actions workflow run can request a signed identity token from GitHub's hosted issuer at `https://token.actions.githubusercontent.com`. With Workload Identity Federation, your workflow exchanges that token for a short-lived Anthropic access token, so your CI jobs can call the Claude API without an `ANTHROPIC_API_KEY` secret stored in your repository.89The token's `sub` claim encodes the repository and trigger context. For a push to a branch it has the form `repo:<owner>/<repo>:ref:refs/heads/<branch>`. Pull-request runs use `repo:<owner>/<repo>:pull_request`, and environment-gated deployments use `repo:<owner>/<repo>:environment:<name>`. Your federation rule matches against this claim (and others, such as `repository_owner` and `ref`) to decide which workflow runs are allowed to authenticate.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 GitHub repository where you can edit workflow files and grant the `id-token: write` permission.15* Permission to create service accounts, federation issuers, and federation rules in the Claude Console for your Anthropic organization.16* Your Anthropic organization ID. You can find it in the Claude Console under **Settings → Organization**.1718## Configure your workflow1920GitHub only issues an identity token to jobs that explicitly request it. Add the `id-token: write` permission at the workflow or job level:2122```yaml23permissions:24  id-token: write25  contents: read26```2728Inside the job, the runner exposes two environment variables: `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`. Call the request URL with the request token as a bearer credential and your chosen audience as a query parameter, then write the returned JSON Web Token (JWT) to a file:2930```yaml31- name: Fetch GitHub OIDC token32  run: |33    curl -sS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \34      "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://api.anthropic.com" \35      | jq -r .value > /tmp/gha-jwt36```3738If you prefer JavaScript, `actions/github-script` exposes the same capability through `core.getIDToken(audience)`:3940```yaml41- name: Fetch GitHub OIDC token42  uses: actions/github-script@v843  with:44    script: |45      const fs = require('fs');46      const token = await core.getIDToken('https://api.anthropic.com');47      fs.writeFileSync('/tmp/gha-jwt', token);48```4950The decoded token carries claims that describe the workflow run. Your federation rule matches against these:5152```json53{54  "iss": "https://token.actions.githubusercontent.com",55  "sub": "repo:your-org/your-repo:ref:refs/heads/main",56  "aud": "https://api.anthropic.com",57  "repository": "your-org/your-repo",58  "repository_owner": "your-org",59  "ref": "refs/heads/main",60  "sha": "abc123...",61  "workflow": "CI",62  "actor": "octocat",63  "event_name": "push"64}65```6667See [GitHub's OIDC subject claim reference](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#example-subject-claims) for the full list of `sub` formats.6869## Configure Anthropic7071In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **GitHub Actions** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.7273The 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):7475**Federation issuer:** GitHub publishes its OIDC discovery document and JWKS publicly, so use discovery mode. Anthropic refreshes the keys automatically when GitHub rotates them.7677```json78{79  "name": "github-actions",80  "issuer_url": "https://token.actions.githubusercontent.com",81  "jwks": { "type": "discovery" }82}83```8485**Federation rule:** Match only the workflow runs you intend to trust. See [Restrict which workflows can authenticate](https://platform.claude.com/docs/en/manage-claude/wif-providers/github-actions#restrict-which-workflows-can-authenticate) for how to scope these claims safely.8687```json88{89  "name": "gha-main",90  "issuer_id": "fdis_...",91  "match": {92    "subject_prefix": "repo:your-org/your-repo:ref:refs/heads/main",93    "audience": "https://api.anthropic.com",94    "claims": {95      "repository_owner": "your-org"96    }97  },98  "target": {99    "type": "service_account",100    "service_account_id": "svac_..."101  },102  "workspace_id": "wrkspc_...",103  "oauth_scope": "workspace:developer",104  "token_lifetime_seconds": 600105}106```107108Be as specific as the workload allows. Loosen `subject_prefix` to `repo:your-org/your-repo:*` (paired with a `claims.ref` constraint) only if the rule must match multiple event types from the same repository, because the trailing segment of `sub` varies between `ref:...`, `environment:...`, and `pull_request` events.109110## Acquire and use a token111112Set the federation environment variables on the job and call the SDK normally. `Anthropic()` reads `ANTHROPIC_IDENTITY_TOKEN_FILE`, exchanges the JWT on the first request, and refreshes the access token automatically before it expires.113114<CodeGroup>115  ```yaml Workflow116  name: Call Claude117  on: push118119  permissions:120    id-token: write121    contents: read122123  jobs:124    call-claude:125      runs-on: ubuntu-latest126      env:127        ANTHROPIC_FEDERATION_RULE_ID: fdrl_...128        ANTHROPIC_ORGANIZATION_ID: 00000000-0000-0000-0000-000000000000129        ANTHROPIC_SERVICE_ACCOUNT_ID: svac_...130        ANTHROPIC_WORKSPACE_ID: wrkspc_...  # required when the rule covers multiple workspaces131        ANTHROPIC_IDENTITY_TOKEN_FILE: /tmp/gha-jwt132      steps:133        - uses: actions/checkout@v5134        - name: Fetch GitHub OIDC token135          run: |136            curl -sS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \137              "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://api.anthropic.com" \138              | jq -r .value > "$ANTHROPIC_IDENTITY_TOKEN_FILE"139        - name: Run your script140          run: |141            pip install anthropic142            python your_script.py143  ```144145  ```bash cURL146  JWT=$(cat /tmp/gha-jwt)147148  RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \149    -H "content-type: application/json" \150    --data @- <<JSON151  {152    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",153    "assertion": "$JWT",154    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",155    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",156    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",157    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"158  }159  JSON160  )161162  ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)163164  curl https://api.anthropic.com/v1/messages \165    -H "authorization: Bearer $ACCESS_TOKEN" \166    -H "anthropic-version: 2023-06-01" \167    -H "content-type: application/json" \168    -d '{169      "model": "claude-opus-5",170      "max_tokens": 1024,171      "messages": [{"role": "user", "content": "Hello, Claude"}]172    }' | jq -r '.content[] | select(.type == "text") | .text'173  ```174175  ```python Python176  import anthropic177178  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,179  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE180  # from the job environment.181  client = anthropic.Anthropic()182183  message = client.messages.create(184      model="claude-opus-5",185      max_tokens=1024,186      messages=[{"role": "user", "content": "Hello, Claude"}],187  )188  print(next(block.text for block in message.content if block.type == "text"))189  ```190191  ```typescript TypeScript192  import Anthropic from "@anthropic-ai/sdk";193194  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,195  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE196  // from the job environment.197  const client = new Anthropic();198199  const message = await client.messages.create({200    model: "claude-opus-5",201    max_tokens: 1024,202    messages: [{ role: "user", content: "Hello, Claude" }]203  });204  for (const block of message.content) {205    if (block.type === "text") {206      console.log(block.text);207    }208  }209  ```210211  ```go Go212  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,213  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE214  // from the job environment.215  client := anthropic.NewClient()216217  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{218  	Model:     anthropic.ModelClaudeOpus5,219  	MaxTokens: 1024,220  	Messages: []anthropic.MessageParam{221  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),222  	},223  })224  if err != nil {225  	panic(err)226  }227  for _, block := range message.Content {228  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {229  		fmt.Println(textBlock.Text)230  		break231  	}232  }233  ```234235  ```java Java236  AnthropicClient client = AnthropicOkHttpClient.fromEnv();237238  var message = client.messages().create(MessageCreateParams.builder()239          .model(Model.CLAUDE_OPUS_5)240          .maxTokens(1024)241          .addUserMessage("Hello, Claude")242          .build());243244  IO.println(message.content());245  ```246247  ```csharp C#248  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,249  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE250  // from the job environment.251  using var client = new AnthropicClient();252253  var message = await client.Messages.Create(new()254  {255      Model = Model.ClaudeOpus5,256      MaxTokens = 1024,257      Messages = [new() { Role = Role.User, Content = "Hello, Claude" }],258  });259  foreach (var block in message.Content)260  {261      if (block.Value is TextBlock textBlock)262      {263          Console.WriteLine(textBlock.Text);264      }265  }266  ```267268  ```bash CLI269  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,270  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE271  # from the job environment.272  ant messages create \273    --model claude-opus-5 \274    --max-tokens 1024 \275    --message '{role: user, content: "Hello, Claude"}'276  ```277278  ```php PHP279  use Anthropic\Client;280281  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,282  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE283  // from the job environment.284  $client = new Client();285286  $message = $client->messages->create(287      model: 'claude-opus-5',288      maxTokens: 1024,289      messages: [['role' => 'user', 'content' => 'Hello, Claude']],290  );291  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');292  echo $textBlock->text, PHP_EOL;293  ```294295  ```ruby Ruby296  require "anthropic"297298  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,299  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE300  # from the job environment.301  client = Anthropic::Client.new302303  message = client.messages.create(304    model: "claude-opus-5",305    max_tokens: 1024,306    messages: [{role: "user", content: "Hello, Claude"}]307  )308  puts message.content.find { it.type == :text }.text309  ```310</CodeGroup>311312Each GitHub-issued identity token expires roughly five minutes after issuance. The token-request endpoint (`ACTIONS_ID_TOKEN_REQUEST_URL`) stays valid for the entire job, so you can fetch a fresh token at any point. The SDK exchanges the token on first use and caches the resulting Anthropic access token. For jobs that run longer than the Anthropic token's lifetime, the SDK re-reads `ANTHROPIC_IDENTITY_TOKEN_FILE` on each refresh, so re-run the fetch step periodically (or wrap it in a background loop) to keep the file current. Alternatively, pass a token-provider callback to the SDK that calls `ACTIONS_ID_TOKEN_REQUEST_URL` directly instead of using the file path.313314## Verify the setup315316A successful exchange returns an `access_token` beginning with `sk-ant-oat01-` and an `expires_in` value in seconds. A denied exchange returns an opaque `401` `authentication_error` with the fixed message `Authentication failed`, whichever check failed; in most cases the deny reason is recorded on the attempt's entry in the [authentication history page](https://platform.claude.com/settings/workload-identity-federation?tab=history), and [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange) walks the checks in order. The most common GitHub Actions-side cause is the `sub` claim format not matching (its trailing segment varies between `ref:...`, `environment:...`, and `pull_request` events); the history entry shows reason `match_subject_prefix`.317318## Restrict which workflows can authenticate319320<Warning>321  A `subject_prefix` of `repo:your-org/*` alone matches every repository in your organization, and without a `ref` constraint it also matches `pull_request` runs triggered from forks. Anyone who can open a pull request against a matching repository could obtain a federated Anthropic token.322</Warning>323324Lock the rule's `match` block to the narrowest scope that fits your use case:325326* **Pin to a single repository:** Use `subject_prefix: "repo:your-org/your-repo:*"` so other repositories in the organization do not match.327* **Pin to a protected branch:** Add `"ref": "refs/heads/main"` (or your release branch) under `claims` so pull-request runs and feature branches do not match.328* **Pin the owner explicitly:** Add `"repository_owner": "your-org"` under `claims` as a defense-in-depth check against `sub` parsing edge cases.329* **Pin to a deployment environment:** For deploy jobs, match `subject_prefix: "repo:your-org/your-repo:environment:production"` and gate that environment with required reviewers in GitHub.330331## Next steps332333* [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation): full setup walkthrough, environment variables, and credential precedence.334* [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication): how federation compares to API keys.335
Files main
Menu

Theme