Skip to main content
Back to all articles
AI Engineering 5 min readUpdated September 18, 2026

Your AI Agent Still Uses One Shared API Key. That’s the Security Problem.

A shared agent credential makes every downstream call look the same and gives one leak far too much power. A better design carries both the user and the agent identity into a short-lived, resource-scoped delegated token.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#OAuth 2.0#Token Exchange#Delegated Identity#Authorization#AI Security#TypeScript#Python#SPIFFE
On this page

A shared API key is easy to ship.

It is also the point where a lot of agent security starts to fall apart.

Suppose a support agent can read invoices, issue refunds, update tickets, and search customer records. If every tool call uses the same long-lived credential, the downstream services only see one caller: the agent.

That creates two problems immediately.

You lose attribution — which user caused this action?

And you lose least privilege — why does a ticketing call need the same credential that can reach billing?

The fix is not another prompt telling the agent to be careful. The fix is to give the agent a real workload identity and exchange that identity, together with the user's identity, for a short-lived token scoped to the service it is about to call.

The model can propose the action. It should not carry the master key.

Carry two identities, not one

There are really two principals involved in an agent tool call:

  • the user the action is being performed for;
  • the agent workload actually making the request.

If you send only the user's token, the downstream service cannot tell that an agent performed the action.

If you send only the agent's credential, you lose the user entirely.

OAuth 2.0 Token Exchange gives us a clean way to carry both. RFC 8693 defines a subject_token for the party on whose behalf the request is made and an optional actor_token for the party doing the acting.

For an agent workflow, that maps naturally to:

Text
subject = user-8472actor   = agent://support-assistant/prod

The resulting token can still have the user as sub, while the agent is recorded in the act claim.

That means the downstream API can finally answer:

Text
who is this for?   user-8472who actually acted? support-assistant/prod

That is a much better audit trail than agent-prod-key called POST /refund.

Put token exchange in front of the tool call

The flow I want is small and boring:

Delegated identity flow

The important part is where the trusted data comes from.

The model may choose the tool and arguments. It should not choose its own userId, tenantId, workload identity, or permissions. Those belong to authenticated application state.

A minimal exchange looks like this:

type ExchangeInput = {  userToken: string;  agentToken: string;  resource: string;  scope: string;};​async function exchangeToken(input: ExchangeInput) {  const body = new URLSearchParams({    grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",    subject_token: input.userToken,    subject_token_type: "urn:ietf:params:oauth:token-type:access_token",    actor_token: input.agentToken,    actor_token_type: "urn:ietf:params:oauth:token-type:jwt",    resource: input.resource,    scope: input.scope,  });​  const response = await fetch("https://auth.internal/oauth/token", {    method: "POST",    headers: { "content-type": "application/x-www-form-urlencoded" },    body,  });​  if (!response.ok) {    throw new Error(`token exchange failed: ${response.status}`);  }​  return response.json();}

The useful controls are the boring-looking fields: resource and scope.

The resource says where the token may be used. RFC 8707 standardizes this pattern so a token can be restricted to the intended protected resource.

The scope says what the token may do there.

So instead of giving the agent one credential that works everywhere, you can mint something closer to:

Text
user:     user-8472actor:    support-assistant/prodresource: https://billing.internalscope:    refund:createexpires:  a few minutes from now

If that token leaks, the blast radius is much smaller than a shared production key.

The token should never go back to the model

This is an easy mistake to make.

You build a proper token-exchange flow, mint a narrow credential, and then place that credential into agent state so the model can pass it to the tool.

Now the model can accidentally expose it in a trace, include it in another tool call, or leak it through a prompt-injected workflow.

The model does not need the token.

Keep it inside the trusted executor:

async function callBillingTool(ctx: {  userToken: string;  agentToken: string;  invoiceId: string;}) {  const delegated = await exchangeToken({    userToken: ctx.userToken,    agentToken: ctx.agentToken,    resource: "https://billing.internal",    scope: "refund:create",  });​  return fetch(`https://billing.internal/invoices/${ctx.invoiceId}/refund`, {    method: "POST",    headers: {      authorization: `Bearer ${delegated.access_token}`,    },  });}

The agent decides *what it wants to do*.

Trusted code decides *which identity and authority are attached to that action*.

That separation matters more than the OAuth syntax.

Give the agent a real workload identity

The actor token also needs to come from somewhere trustworthy.

A static secret in an environment variable is better than nothing, but it still leaves you with another long-lived credential to protect and rotate.

A workload identity system such as SPIFFE/SPIRE is a stronger model. The workload can receive a short-lived SVID tied to a SPIFFE ID, rather than shipping a permanent secret with the application.

The important rule is simple:

The agent's identity comes from infrastructure, not from model output.

If a prompt says, "pretend you are the finance agent," that should have zero effect on the identity used for authorization.

Make the downstream API care about the delegation

Minting a good token is only half of the design.

The resource server still needs to validate it and authorize the actual operation.

At minimum, I want it to check the expected issuer, expiry, audience/resource, scope, subject, and current actor.

Then the audit event becomes useful:

JSON
{  "subject": "user-8472",  "actor": "agent://support-assistant/prod",  "resource": "billing",  "scope": "refund:create",  "invoiceId": "INV-4821"}

Now "who did this?" has a real answer.

A valid token still does not mean every refund is allowed. Business rules such as tenant ownership, refund limits, approval requirements, and invoice state still belong in application authorization.

Identity gives the policy engine trustworthy inputs. It does not replace the policy engine.

A few production details that matter

Short-lived tokens expire during long-running agent tasks. Re-exchange when needed instead of making them long-lived just for convenience.

Token exchange also adds a network hop. A small cache can be reasonable, but key it by the authority being reused — for example user, resource, and scope. If you cache one token per service, you can quietly recreate the shared-key problem you were trying to remove.

Retries are separate from identity. If a refund succeeds and the HTTP response is lost, a fresh token does not stop the agent from issuing the refund twice. Use idempotency for side effects.

And for risky actions with human approval, mint the credential after approval, not before it. If the action changes, authorize and exchange again.

The takeaway

A shared agent key is convenient because it hides all the identity work.

That is also why it is dangerous.

Once an agent acts on behalf of real users, I want every downstream call to carry two facts: which user the action belongs to, and which workload actually performed it.

Authenticate both. Check the requested action. Exchange into a short-lived token for one resource with the smallest useful scope. Keep that token inside trusted execution code, and make the resource server enforce what it means.

The agent can stay flexible without becoming the place where identity and authorization are invented.

References

KEEP READING

Related engineering notes