OAuth token exchange for AI agents: Acting on behalf of a user

by Sujay ChoubeyNov 20, 202614 min read
AI AgentsAuth

TL;DR: Use RFC 8693 when a downstream API trusts your token issuer and an AI agent needs authority to act on behalf of a user. Delegation preserves both the user's and the agent's identities through the act claim, but the Security Token Service (STS) must validate their relationship and enforce permissions. Building and maintaining an STS costs more than the token endpoint itself: it also requires issuer trust, policy enforcement, tenant isolation, key management, monitoring, and ongoing maintenance. For teams that would rather offload provider credential management, Composio handles connected-account authentication and tool execution across 1,500+ apps, though RFC 8693 support should be verified separately before using any managed integration layer as an STS.

When an AI agent sends email, updates a CRM record, or pushes code on a user's behalf, a standard OAuth flow may provide the initial user token without establishing how downstream services distinguish the agent from the user. RFC 8693 defines how a service can exchange an existing token for one suited to a downstream resource. Before deploying an STS, plan for issuer trust, delegation policy, credential lifecycle management, and audit logging.


AI agent completing a cross-app task, pulling Google Analytics data and writing results to a spreadsheet, with tool-call chips for connected apps.

This guide walks through the exchange flow, the security distinction between impersonation and delegation, and the actor claim that makes delegation auditable. Then it explains the work involved in operating a self-hosted token service, so you can make a defensible build-vs-buy decision using your own engineering estimates.

Understanding the RFC 8693 exchange flow

RFC 8693 is the IETF specification defining the token-exchange grant type used by a Security Token Service (STS). Instead of an agent carrying a long-lived user token into every downstream call, it presents that token to the STS and receives a new token scoped to a specific audience and task.

How RFC 8693 token exchange works

RFC 8693 defines the grant type, urn:ietf:params:oauth:grant-type:token-exchange, which distinguishes exchange requests from other OAuth 2.0 token requests. The flow works like this:

  1. Subject token presentation: The agent presents a subject_token (the user's existing token) to the STS.

  2. Validation: The STS validates the subject token against policy.

  3. Actor token (for delegation): The agent also presents an actor_token identifying itself.

  4. Token issuance: The STS issues a new token, narrowed to the target resource and scopes.

The STS returns an OAuth 2.0 token response that includes issued_token_type to identify the type of token issued.

Managing scoped access for AI agents

Token exchange is designed to narrow permissions, but scope reduction is a policy decision rather than a protocol guarantee. The authorization server decides which permissions to grant. RFC 8693 section 5 (security considerations) warns against issuing tokens with broader authority than the source token allows. Restrict each delegation hop to the intended resource and task, and enforce those limits at the STS. An agent authorized to send an email should not also receive permission to delete calendar events.

Keycloak's token exchange documentation describes audience filtering and scope handling. Confirm the behavior of your deployed version before relying on it for downscoping.

Token exchange versus standard OAuth flows

Standard OAuth flows, such as Authorization Code and Client Credentials, handle user authorization or service-to-service access. Token exchange assumes a token already exists and asks the STS to transform it for a new context, which is why it fits multi-tier architectures where middleware calls downstream APIs without forwarding the user's original token.

Microsoft Entra ID's on-behalf-of flow documentation describes a related scenario using a JWT bearer grant and requested_token_use=on_behalf_of, but it is not the RFC 8693 grant. An STS can issue downstream tokens only for APIs that trust its issuer and token format. For third-party APIs, a managed auth layer such as Composio can instead store provider-issued credentials and attach them to authorized API requests.

When to use impersonation versus token delegation

RFC 8693 defines two semantics with very different security properties, and the choice determines whether your audit trail survives an incident.

How impersonation affects attribution

In an impersonation flow, the issued token represents the subject without separately identifying the actor. The downstream service cannot identify the intermediary from an act claim, although other token metadata or service logs may provide context. This preserves compatibility with legacy APIs. It also means a compromised intermediary is harder to distinguish from the user during an investigation.

How delegation preserves actor identity

In this delegation design, the request includes an actor token. The STS validates both tokens, checks that the actor is authorized (via the may_act claim on the subject token or server policy), and issues a composite token naming both parties. The downstream API can distinguish the user from the acting agent, as Ping Identity’s token exchange documentation explains. For useful attribution, the resource server must inspect and log both identities.

Trade-offs and when each applies

Delegation makes the actor explicit, but it does not automatically constrain permissions or produce an audit log. The STS must enforce access policy, and downstream services must record the subject, actor, action, and outcome.

Use impersonation only when the intermediary is trusted and separate actor attribution is not required, such as an internal service calling a legacy API. Choose delegation when downstream services need to distinguish the agent from the user it represents. Keycloak documents a delegation implementation, but the feature is currently preview, disabled by default, and not fully supported.

Securing cross-service delegation with actor claims

The act claim supplies actor identity that downstream services can include in audit records.

How actor claims identify delegation

The act claim is a JSON object that identifies the acting party in a delegated token. A minimal delegated token looks like this:

{
  "sub": "user@example.com",
  "act": {
    "sub": "agent@yourco.dev"
  },
  "aud": "https://mail.example.com",
  "scope": "email.send"
}

The sub field identifies the user whose authority is being exercised, and act.sub identifies the acting agent.

RFC 8693 section 4.4 defines may_act, which identifies a party authorized to act for the subject. The STS can use that claim when deciding whether to permit an exchange. It is one authorization mechanism, not a mandatory claim for every deployment, and it does not replace scope or audience enforcement.

Logging OAuth token exchange events

Log each token issuance event, including the agent, the represented user, the requested scope, and whether the exchange succeeded. STS logs provide a central record of delegated authority granted, whether or not a downstream request succeeds. To verify whether an agent sent an email, correlate the exchange record with the downstream action log. That combination provides evidence of both granted authority and execution for an access-control review such as a SOC 2 Type II audit.

Composio’s trust center provides its compliance documentation.

RFC 8693 token exchange workflows

For nested delegation, token consumers must base authorization decisions on the token's top-level claims and the current actor, not prior actors in the chain. RFC 8693 section 4.1 specifies this processing rule, and section 5 discusses the corresponding security considerations. This prevents a compromised intermediary from relying on historical actors in the chain to claim authority it does not have. If you chain exchanges across microservices, enforce this at every resource server, and treat any deviation as a finding.

Configuring OAuth token exchange for agents

A working delegation flow has four steps and a fixed set of request parameters.

Request delegated access tokens

The agent POSTs the exchange request to the STS:

POST /token HTTP/1.1
Host: sts.example.com
Content-Type: application/x-www-form-urlencoded

<p>grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token=eyJhbGciOi...
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&actor_token=eyJraWQiOi...
&actor_token_type=urn:ietf:params:oauth:token-type:access_token
&resource=<a href="https://mail.example.com">https://mail.example.com</a>
&scope=email.send</p>

Use resource to identify the intended API and scope to request permissions for the current task. The STS must enforce the allowed target and scope. This sample omits deployment-specific client authentication, and the form values must be URL-encoded in an actual request.

Validate RFC 8693 tokens

For this delegation design, configure the STS to:

  • Validate both tokens using the checks appropriate to their type, including signature verification for signed tokens or introspection for supported opaque tokens.

  • Confirm the actor appears in the subject token's may_act claim, or policy otherwise authorizes the exchange.

  • Check the requested scope is a subset of the subject token's scope (no privilege escalation).

  • Ensure the requested audience is one the actor may access.

The authorization server must verify that a client is authorized to impersonate or act for the specific subject, as required by RFC 8693 section 5.

Complete the RFC 8693 token grant

When validation passes, the STS returns a composite token carrying both identities, the narrowed audience, and the reduced scope. Choose a short token lifetime appropriate to the risk. A 15-to-60-minute token lifetime is an illustrative deployment choice, not an RFC requirement. New exchanges can apply updated policy, but already issued tokens may remain valid until expiry unless the resource server enforces revocation or another runtime check.

Route requests with delegated tokens

The agent calls the downstream API using the delegated token as a bearer credential. The resource server verifies the signature against the STS public key, inspects sub and act, applies actor-aware policy, and logs both identities. Bind tokens to tenant context and reject a token issued for tenant A when a request targets tenant B.

Request parameters for token exchange

Parameter

Required

Example value

grant_type

Yes

urn:ietf:params:oauth:grant-type:token-exchange

subject_token

Yes

User's access token

subject_token_type

Yes

urn:ietf:params:oauth:token-type:access_token

actor_token

For delegation

Agent's access token

actor_token_type

If actor present

urn:ietf:params:oauth:token-type:access_token

resource / audience

Recommended

https://mail.example.com

scope

Recommended

email.send

requested_token_type

No

Server chooses if omitted

Plan for these possible responses. RFC 8693 section 2.2.2 specifies invalid_request for invalid subject or actor tokens and recommends invalid_target for unacceptable target services. Other OAuth errors can also apply.

Failure mode

HTTP status

Handling strategy

Invalid or expired input token

400 invalid_request

Identify the rejected token, then refresh or re-authenticate as supported

Scope mismatch

400, such as invalid_scope

Reduce scope or obtain consent through a separate supported flow

Unacceptable resource or audience

400 invalid_target

Correct the target and verify issuer trust

STS unavailable

503 or transport failure

Use bounded retries, and retry writes only with duplicate-prevention controls

Estimating the effort of auth infrastructure

Teams underestimate token services because the visible part (one exchange endpoint) is small. Most of the work lies in the credential lifecycle and operational controls around that endpoint.

Hidden costs of token lifecycle management

A production OAuth integration involves app registration, consent flows with state handling, encrypted token storage, refresh coordination, revocation handling, and a connect-disconnect interface.

An STS adds issuer trust, subject and actor validation, tenant isolation, key management, authorization policy, monitoring, and high availability. Size the work by your provider count, tenancy model, existing identity infrastructure, security requirements, and engineering capacity. Without a documented internal estimate, a universal hour figure is misleading.

Managing RFC 8693 audit logs

Build time is only the beginning. Ongoing maintenance includes provider API changes, refresh edge cases, credential revocation, scope changes, incident response, and audit evidence. Because the STS sits upstream of connected services, changes to a provider’s authentication model can affect every agent using that integration. Include these recurring responsibilities in the decision, not just the initial implementation.

Evaluating RFC 8693 implementation effort

Estimate your own implementation in phases, starting with a minimal single-tenant exchange service, then a production-ready service with token validation, key rotation, monitoring, and incident handling, and, where needed, a multi-tenant layer with tenant isolation and policy enforcement. Then budget recurring maintenance by integration, including provider changes and security reviews. The more connected applications you operate, the more important it becomes to measure that ongoing work against a managed alternative.

Self-hosting an identity server gives your team control over token issuance, but also responsibility for patching, policy configuration, availability, and audit evidence. Product licensing and dependencies still apply.

Aembit’s documentation describes workload access policies that use verified workload identity and context to provision credentials. That is a related identity-control pattern, not proof that every managed integration product implements RFC 8693. Compare token issuance, provider credential handling, and tool execution as separate requirements.

Offloading token lifecycle to managed auth

Maintaining provider consent flows, token storage, refresh, and authenticated API calls adds work to every integration. A managed auth layer can take on those tasks. Whether it also provides an RFC 8693 STS must be established from that product's documented protocol support.

Token Vault role in RFC 8693 flows

Auth0's Token Vault stores external-provider access and refresh tokens and lets applications retrieve provider tokens through supported exchange flows. Composio's managed authentication stores and refreshes connected-account credentials and attaches them to provider requests server-side. These are related credential-brokering capabilities, but they do not establish interchangeable token formats or RFC 8693 support. Pelago Health uses this approach for 160 internal agents: users authorize connected applications, Composio manages the credentials, and agents do not need to handle the tokens directly.

Handling RFC 8693 flows at scale

When an agent holds authentication state, every provider’s OAuth flow, token refresh, and credential storage becomes a maintenance burden that grows with each integration. A leaked token can also reach the model context. Composio removes that burden by handling OAuth flows, credential refresh, and proxy execution centrally, so the agent never holds authentication state. This applies across more than 50,000 agent-ready tools in 1,500+ apps and integrations.

Composio encrypts stored credentials with AES-256-GCM and uses them when executing tool calls. Developers can configure per-action permissions for each session, and Composio checks those permissions before a tool call reaches the external API. The Logs API reports tool execution outcomes. Confirm which actor, user, policy, and outcome fields your deployment records and exports. To verify that an RFC 8693 act claim was propagated, inspect the token issued by the exchange.

Spinnable connected roughly 100 integrations using Composio, reducing integration time from a week to hours. Atomic Agent relies on Composio to manage integrations with more than 50 apps, allowing its engineers to focus on the agent. Composio documents its SOC 2 Type II and ISO 27001:2022 certifications in its trust center, with certification scope described in its compliance scope clarification.

A single-integration product may not need a managed integration catalog, so compare the ongoing costs directly. Confirm deployment location and contractual data-residency requirements before choosing a hosted service. Start on the free tier with 20,000 Composio-managed tool calls per month and test your first integration without a sales call, subject to the current plan terms.

The Microsoft OAuth scope guide describes tenant consent and scope management. The managed authentication documentation covers internal tools.

When to offload token management

Offload when any of these are true:

  1. A growing integration roadmap: each added provider brings consent, token storage, refresh handling, troubleshooting, and change monitoring. Compare the measured cost of this work with the coverage of a managed integration catalog.

  2. Per-user delegation with different permissions: evaluate managed consent, scope controls, and the user and actor fields available in execution logs.

  3. Enterprise reviews on the horizon: Composio's SOC 2 Type II and ISO 27001:2022 certifications, documented in its trust center, give your team evidence it can review and cite in security responses.

  4. Velocity is the constraint: the build-vs-buy decision matrix below summarizes the trade.

Criterion

Self-hosted STS

Managed IdP (Entra ID)

Composio managed auth

Initial build

Scope depends on tenancy, trust configuration, and security requirements

Depends on identity and API requirements

Configuration plus application integration

Maintenance

Your team maintains the STS and each provider connection

Your team maintains application integration

Provider integration maintenance is managed

Audit logging

You design and operate it

Verify identity, workload, and downstream log coverage

Verify available tool-call execution records

Certifications

Your audit

Microsoft's, not yours

SOC 2 Type II, ISO 27001:2022

Portability

Your code, configuration, and dependencies

Provider-specific identity configuration

Review SDK, connection, and credential migration options

Book a call to walk through your security requirements.

FAQs

Does every SaaS API support token exchange?

No. An API can accept an exchanged token only if it trusts that token's issuer and supports its format, audience, and authorization semantics. You cannot mint your own STS token and expect an arbitrary SaaS API to accept it. For APIs that require provider-issued OAuth tokens or API keys, use the provider's supported credentials, potentially through a managed authentication proxy.

Can I use RFC 8693 with existing OAuth flows?

Yes. Authorization Code with PKCE can obtain an initial user token, which a compatible STS may then accept as a subject token. You still need to configure trust, client authorization, downstream audiences, and permitted scopes. Additional consent may be required by your provider or application policy.

What happens when a delegated token expires?

The client requests another token using the exchange or refresh mechanism supported by its deployment. Refreshing an expired subject token is a separate capability, and RFC 8693 does not require the STS to store a user refresh token or refresh it transparently. If credentials or authorization are no longer valid, the client must reconnect or obtain consent as required.

How do I revoke a delegated token?

Use the issuer's supported revocation controls, including RFC 7009 (OAuth 2.0 Token Revocation) where implemented. Blocking future exchanges, changing may_act, or revoking the original token does not automatically invalidate every token already issued. Resource servers may need introspection, a denylist, or another runtime check to reject an existing token before expiry. Record both the revocation request and its verified enforcement in your audit trail.

Key term glossary

Token exchange: The RFC 8693 mechanism for obtaining a token for a different audience or scope, subject to STS policy, using the grant type urn:ietf:params:oauth:grant-type:token-exchange.

Impersonation: A token represents the subject without preserving a separate actor identity. Attribution may require other token metadata or service logs.

Delegation: Authority exercised by an actor on behalf of a subject. An act claim can preserve the actor identity for downstream policy and logging.

Actor claim: The act JWT claim expressing that delegation occurred and naming the acting party in its nested sub field.

Subject token: The existing token presented to the STS for exchange, typically the end user's access token or a SAML assertion.

Get started

Your agents can
do more

Connect your agents to 1,700+ apps. Start for free, no credit card needed.

Are you an AI agent? See setup options

Share