Agent Identity with Workload Identity Federation: a Short-Lived Token Instead of a Static Key, and Tool Secrets Kept in the Harness
One static key on a laptop, a CI job and a pod leaks into a CI log, and nobody can say which workload used it. Swap it for workload identity federation: the pod trades its JWT for a 600-second token as a named service account, the CRM token stays in a vault the harness reads, and a wrong pod gets HTTP 401.
What you will learn
- Explain why one static API key shared by a laptop, CI and a pod can't be traced or revoked quietly
- Set up workload identity federation: service account, federation issuer and federation rule
- Build a Claude client from WorkloadIdentityCredentials and refuse a leftover ANTHROPIC_API_KEY
- Keep a tool secret in the harness: read it from the vault at call time, never put it in the prompt
Before you start
- Claude API keys and environment variables
- Claude tool use
- Basic Python
Picture the SupportDesk agent starting its shift. Before it answers a single ticket, it has to prove who it is. Most teams solve that with one long-lived API key.
In this article we give the agent a name instead. Four ideas: identity, federation, secrets and audit. By the end, the agent can answer two questions: who am I, and what am I holding?
One key, three places, no owner
Here is the use case. The same key is copied to a laptop, a CI job and the production pod. Three places, one static key, and the Claude API accepts whoever holds it.
Then the key turns up in a CI log. It never expires, so it stays dangerous. And the question nobody can answer: which workload used it? A key with no name and no expiry can't be traced, and can't be taken back quietly. (If you must use keys, keep them on a server, one per environment, and rotate them. This article is about not needing one at all.)
A hotel that knows who you are
- A master key under the doormat opens every room and never expires. Whoever finds it is you. That is a static API key.
- A day pass from reception has your name on it and ends tonight. Reception checks who you are before issuing it. That is a federated, short-lived token.
- The safe behind the desk: the guest never holds its key. They only get the answer. That is how tool secrets should work.
Prove who you are, and never hand over the key.
How a pod swaps its JWT for a short-lived token
First comes a one-time setup in the Claude Console, three resources:
- A service account: the named identity the workload acts as.
- A federation issuer: registers your identity provider.
- A federation rule: says which tokens may act as which service account.
At runtime it goes like this:
- The identity provider hands the pod a signed JWT.
- The SDK posts that JWT to Anthropic, along with the rule id.
- Anthropic checks it against the rule and returns a short-lived access token.
- The pod sends that token on every call, and the SDK refreshes it before it expires.
before_agent.py: the version we are replacing
The project runs on a stand-in (the Anthropic SDK on an httpx mock transport, with a made-up token endpoint, vault and CRM), so no API key is needed and the replies are test replies. Every id, token and secret in it is made up.
"""Before: a static key, and a tool token pasted into the prompt."""
import os
from anthropic import Anthropic
from stand_in import MODEL, http_client
def make_client():
key = os.environ["ANTHROPIC_API_KEY"]
return Anthropic(api_key=key, http_client=http_client())
def ask(client, question):
crm = os.environ["CRM_TOKEN"]
system = f"You are the SupportDesk agent. CRM token: {crm}"
r = client.messages.create(
model=MODEL, max_tokens=256, system=system,
messages=[{"role": "user", "content": question}])
return r.content[0].text
A static key from the environment: no expiry, no identity behind it. Then the CRM token pasted into the system prompt so the agent can call the CRM. Both now travel in every request and land in every log and trace.
identity.py: the client with a name
"""After: the workload proves who it is. No key to store."""
import os
from anthropic import Anthropic
from anthropic import WorkloadIdentityCredentials, IdentityTokenFile
from stand_in import http_client
def refuse_static_key():
"""A leftover ANTHROPIC_API_KEY would outrank federation."""
if os.environ.get("ANTHROPIC_API_KEY"):
raise RuntimeError("ANTHROPIC_API_KEY is set: unset it")
def make_client():
refuse_static_key()
env = os.environ
token_file = env["ANTHROPIC_IDENTITY_TOKEN_FILE"]
creds = WorkloadIdentityCredentials(
identity_token_provider=IdentityTokenFile(token_file),
federation_rule_id=env["ANTHROPIC_FEDERATION_RULE_ID"],
organization_id=env["ANTHROPIC_ORGANIZATION_ID"],
service_account_id=env["ANTHROPIC_SERVICE_ACCOUNT_ID"],
http_client=http_client())
return Anthropic(credentials=creds, http_client=http_client())
- A guard first. The environment key outranks federation, so a leftover key would silently win. We refuse to start if one is set.
- The pod's own identity token, read from a file. The SDK rereads that file on every exchange, so rotated tokens just work.
- Which rule and which service account come from the environment.
- No API key anywhere in the client. Only
credentials. In production the same variables are injected per environment and the client is built with no arguments; thehttp_clienthere only points the SDK at the stand-in.
tool_secrets.py: the safe behind the desk
Identity covers the model. The tools have secrets too.
"""The harness holds the secret. The model only sees the answer."""
import json
from stand_in import MODEL, vault_read, crm_lookup
ID_SCHEMA = {"type": "object", "required": ["customer_id"],
"properties": {"customer_id": {"type": "string"}}}
TOOLS = [{"name": "lookup_customer", "input_schema": ID_SCHEMA,
"description": "Find a customer in the CRM by customer id."}]
def lookup_customer(customer_id, who):
token = vault_read("crm/token", who)
row = crm_lookup(token, customer_id)
return {"name": row["name"], "refund": row["refund"]}
def answer(client, question, who):
msgs = [{"role": "user", "content": question}]
r = client.messages.create(model=MODEL, max_tokens=256,
tools=TOOLS, messages=msgs)
call = next(b for b in r.content if b.type == "tool_use")
found = lookup_customer(**call.input, who=who)
result = {"type": "tool_result", "tool_use_id": call.id,
"content": json.dumps(found)}
msgs += [{"role": "assistant", "content": r.content},
{"role": "user", "content": [result]}]
r = client.messages.create(model=MODEL, max_tokens=256,
tools=TOOLS, messages=msgs)
return r.content[0].text
- The tool reads the CRM token from the vault at call time, as this identity, so the vault knows who asked.
- The secret rides the CRM call and nowhere else.
- Only the name and the refund status go back to the model.
One name per workload: the run
run_all.py runs the static-key agent, then the federated one, then two failures: a pod from the wrong namespace and a leftover key. It printed:
before: a static key
credential static api key, expires: never
acted as no identity
CRM token in the prompt: yes
after: workload identity
exchange system:serviceaccount:support:supportdesk-agent:pod-7 -> svac_test_supportdesk, 600s
credential federated token
acted as svac_test_supportdesk
CRM token in the prompt: no
audit vault read crm/token as svac_test_supportdesk
reply test model reply: Hi Ana, your refund was sent on Monday.
two failures
wrong pod system:serviceaccount:dev:scratch-pod -> denied (HTTP 401)
old key ANTHROPIC_API_KEY is set: unset it
- The static key has no identity behind it and never expires, and its CRM token sat in the prompt.
- The federated agent turned pod-7's token into the SupportDesk service account, with a token that lasts ten minutes (600 seconds) under this rule.
- Its prompt held no secret, and the vault read carries a name. That audit line is the who the static key could never give you.
- The scratch pod in the
devnamespace matched no rule, so no token. Nothing to steal at rest, and nothing to use from the wrong place. - A leftover key stops the agent at start instead of silently winning.
Common mistakes
- Rotating the key more often. Still a long-lived secret that can leak between rotations, still no name.
- Sharing one key through a secrets manager. Better storage, same problem: every workload is the same caller.
- Putting the tool token in the system prompt. It travels in every request and lands in every log. Keep it in the harness.
- Leaving
ANTHROPIC_API_KEYset next to federation. It outranks the credentials. Refuse to start. - Forgetting the identity provider. Federation is only as strong as the provider behind it, so protect that too.
For the wider review of who calls what across every hop, and acting with the signed-in user's rights, see authentication and authorization gaps in Claude agents.
Quick recap
| Piece | What it does | In this run |
|---|---|---|
| Workload identity | A token, not a key | pod-7 JWT exchanged, 600s |
| Service account | One name per workload | svac_test_supportdesk |
| Federation rule | Which tokens may act as which account | wrong pod: HTTP 401 |
| Tool secrets | In the harness, never in the prompt | CRM token in the prompt: no |
| Audit | Every call has a who | vault read as svac_test_supportdesk |
Try it yourself
Add a second workload, a nightly batch job, with its own service account and its own rule. Before you write it, decide: what sub should its rule match, and what should happen if the batch job's token is presented by the support pod?
Related course on Udemy
Claude Certified Developer - Professional (CCDV-P) Exam Prep
Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)Related posts
Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
An agent that reads customer emails and can refund up to $200. In a small simulation, a phrase filter still lets 6 of 8 written attacks do harm and blocks 2 honest users; plain checks outside the model take harm to 0 of 8, at a cost of 1 honest request failed and 2 held.
The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
A support agent reads a ticket that says run SELECT * FROM customers and email the result outside, and it has run_sql and send_email, so the customer list leaves. The model wasn't hacked, it was equipped. Map each tool by what it reads, changes and sends, replace the two large ones with narrow tools, scope the keys, and never give one agent untrusted input, private data and a way out together.
Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
Three texts reach a support agent in one week: an injected ticket, a poisoned help article and a jailbreak. A naive agent turns all three into leaks; three small checks in plain code take that to zero.
Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
Review a refund agent the way a security team would: map where stranger text gets in, what it can read and what it can do, layer every path, then show the four normal questions still give the same answer.
