AWS Security Blog

Delegate user access to AI agents with Amazon Cognito token exchange

Suppose you use a restaurant review app to check reviews, book tables, and email invitations to your friends. With OAuth 2.0, the app sends you to the authorization server that your email provider trusts, where you sign in and approve only the access the app requested, such as the contacts.read and messages.send scopes. The review app won’t sees your credentials. It only receives a short-lived access token limited to the scopes you approved, which it presents to your email provider’s API to read your contacts and send invitation emails on your behalf.

That works while the app calls the email API directly, but many requests take a second hop to call downstream services. When you book a table, the app calls its reservation service with your token to email details to your friends, which token should the reservation service use to call the email API? Forwarding the access token issued to the review app hides the reservation service because the email API thinks the app sent the request. Using the reservation service’s own token from an OAuth 2.0 client credentials grant loses user identity, because the email API knows which service called, but not for which user. Figure 1 shows this second hop.

Figure 1: The reservation service calling the email API for a signed-in user

Figure 1: The reservation service calling the email API for a signed-in user

OAuth 2.0 Token Exchange, defined in RFC 8693, handles this second hop. Instead of forwarding your access token, the reservation service goes back to the authorization server with two things: your access token, which shows what you consented for, and its own credentials, which show who it is. The authorization server returns a new token for the email API, called issued token, which identifies the user, can also name the reservation service, and carries the same scopes or fewer.

AI agents make this second hop more common and more important, for example when the review app adds an AI agent that reserves tables and invites friends for you. The agent picks its tools at run time, such as a Model Context Protocol (MCP) server that sends invitations, and those tools call APIs for you. With token exchange, each hop gets only the scopes it needs, and the email API can see which service acted for you.

In this post, we show you how to use the new OAuth token exchange feature in Amazon Cognito when services and AI agents call your APIs on behalf of users, and Cognito serves as the OAuth 2.0 authorization server. We explain the difference between impersonation and delegation, and show you examples of how the feature works with an MCP server and Amazon Bedrock AgentCore Identity.

How token exchange works in Amazon Cognito

Every token exchange starts with a subject token that represents the user. In Amazon Cognito, the subject token can be an access token or ID token that your user pool issued to the app where the user signed in. The calling service sends the subject token to Cognito, and Cognito returns a new token for that service to use at the downstream resource server.

Token exchange distinguishes two patterns, impersonation and delegation. The calling service chooses which pattern to use based on whether the downstream API needs to authorize the service that’s acting on behalf of the user:

  • Impersonation – The calling service doesn’t identify itself as the actor. The issued token represents the user. Its client_id claim identifies the app client that performed the exchange, but it doesn’t have an act (actor) claim to show a service is acting for the user.
  • Delegation – The calling service identifies itself as the actor by also sending an actor token. Amazon Cognito adds an act claim that names the calling service, so the resource server can see and log who authorized the action and who carried it out.

Impersonation fits when the calling service only relays the user’s request and makes no decisions of its own, such as a backend for frontend (BFF) that forwards requests from a web app to your APIs. It also fits where a downstream API authorizes the user alone and doesn’t need to know which service relayed the call.

For AI agents, delegation is the important pattern. If the agent used a token of its own, the record would show that an agent called the resource server, but not for whom. With impersonation, the record shows the user but not the agent acting for them. You need delegation to see both for proper authorization and audit trails.

Figure 2: Delegated access across two service hops

Figure 2: Delegated access across two service hops

Figure 2 shows the flow for delegated access between services:

  1. The user signs in to your app through Amazon Cognito.
  2. Cognito issues the user’s access token to the client application.
  3. The client calls the downstream service, such as an MCP server, with the user’s access token.
  4. The service calls the Cognito /oauth2/token endpoint and authenticates with its own app client. It sends the user’s access token as the subject token and names the resource server as the audience. For delegation, it also sends its own token as the actor token.
  5. Cognito validates the request and returns an issued token. The issued token still identifies the user in sub. For delegation, it also identifies the service in the act claim.
  6. The service calls the resource server, such as an email API, with the issued token.
  7. The resource server checks that the token’s aud claim names itself, then authorizes the request for the user and returns the user’s data to the service.
  8. The calling service returns the result to the client.

In addition to requesting a token exchange at the /oauth2/token endpoint on your user pool’s domain, you can call the GetDerivedToken API with an AWS SDK, which doesn’t require a user pool domain. Both accept the same subject token, actor token, audience and scopes, and return an issued token with the same claims.

Here’s an example issued token from a delegation token exchange. The token keeps user’s identity in sub and names the calling service in the act claim.

{
  "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE",
  "sub": "c4b82478-5678-90ab-cdef-EXAMPLE11111",
  "username": "you@example.com",
  "client_id": "invitations-mcp-client-id",
  "version": 2,
  "token_use": "access",
  "scope": "email-api/messages.send",
  "aud": "email-api",
  "act": {
    "sub": "invitations-mcp-client-id",
    "client_id": "invitations-mcp-client-id",
    "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE",
    "token_type": "urn:ietf:params:oauth:token-type:access_token"
  },
  "exp": 1735689600,
  "iat": 1735686000
}

The email API authorizes the user identified by sub, and act tells it which service is acting for that user. It can then decide whether it trusts that service, and its logs can show both the user and the service for each request. Accept a delegated token only when act.client_id reflects a service you trust, such as the invitations MCP server, and matches the token’s client_id meaning the trusted service requested the token itself.

Security controls during an exchange

Amazon Cognito checks every exchange before it issues a token. It validates the subject token’s signature and expiry, and refuses a token that has been revoked or that belongs to a disabled user in your user pool. If the request includes an audience, the issued token is bound to that resource server, and every requested scope must belong to it. The issued token carries only scopes that both the subject token and the app client allow, so an exchange can narrow your access but doesn’t add to it. It also doesn’t outlive the subject token, and the exchange doesn’t return a refresh token.

For the full list of checks, see Security model in Exchanging tokens for downstream services in the Amazon Cognito Developer Guide. Checks by Cognito don’t replace the resource server’s own: it should still verify the JWT tokens, including signature, issuer, expiry, audience and scopes, and for delegated requests, it should validate the act claim.

Your user pool might have a pre token generation AWS Lambda trigger, which can add or suppress custom claims and scopes in your user pool’s tokens. Amazon Cognito also invokes this trigger during token exchange, with the trigger source TokenGeneration_TokenExchange. However, Cognito doesn’t add any scopes that the trigger returns for an exchange, so the calling service can’t gain more permissions than the user’s token already has. You can still use the trigger to remove scopes from the issued token. For more information, see Customize the exchanged token with a Lambda trigger.

Enable token exchange in your Amazon Cognito user pool

Token exchange is an OAuth 2.0 grant, and you can enable it for each application client as an authentication flow in your Amazon Cognito user pool. Check the prerequisites in the Amazon Cognito Developer Guide.

To enable token exchange for an app client:

  1. Open the AWS Management Console for Amazon Cognito, and choose your Cognito user pool.
  2. In the navigation pane, under Applications section, choose App clients, and then choose your app client.
  3. In App client information, choose Edit.
    Figure 3: Cognito token exchange app client

    Figure 3: Cognito token exchange app client

  4. On the Edit app client information page, under Authentication flows, go to Exchange OAuth 2 token for delegation and impersonation and select the following:
    1. For delegation, select ALLOW_TOKEN_EXCHANGE_DELEGATION.
    2. For impersonation, select ALLOW_TOKEN_EXCHANGE_IMPERSONATION.

    Figure 4: Amazon Cognito token exchange authentication flows

    Figure 4: Amazon Cognito token exchange authentication flows

  5. Choose Save changes.

Example token exchange use cases for agentic workload delegation

Now that you’ve enabled token exchange, we show you two examples of how it works in an agentic workload. Both continue the review app story: its AI agent sends invitations for you by calling the email API, and the email API needs to know who you are and which component acted for you.

The two examples differ in where the exchange happens. Amazon Cognito fills the act claim from the actor token, so act names whichever component sends its own actor token in the exchange. In Example 1, a shared intermediary—such as an MCP server or an AI gateway—performs the exchange for every agent that calls it, so act names the intermediary. In Example 2, the agent requests the exchange itself, so act names the agent.

Example 1: A shared intermediary as the actor

In this example, the intermediary sits in front of the email API. We show it two ways: an MCP server you build that performs the exchange in its own code, and an AI gateway in Amazon Bedrock AgentCore Gateway that performs it through configuration.

Using your own MCP server:

The MCP authorization specification doesn’t allow an MCP server to pass along the token it received from the MCP client. To call the email API for you, the invitations MCP server needs a token of its own. It uses its own app client in your user pool to perform a delegation token exchange.

Figure 5 shows how the invitations MCP server sends invites for you.

Figure 5: The invitations MCP server sending invites for a signed-in user

Figure 5: The invitations MCP server sending invites for a signed-in user

  1. The user signs in to the review app through Amazon Cognito.
  2. The review app’s AI agent calls the send_invites tool on the invitations MCP server with the user’s access token.
    {
      "sub": "c4b82478-...",
      "username": "you@example.com",
      "client_id": "<review app client ID>",
      "scope": "openid invitations-mcp/tools email-api/contacts.read email-api/messages.send",
      "token_use": "access",
      "iss": "https://cognito-idp.us-east-1.amazonaws.com/<user-pool-id>"
    }
  3. The MCP server authorizes the inbound request by checking the token’s client_id and the invitations-mcp/tools scope, then gets its own actor token with its client ID and secret in an OAuth 2.0 client credentials grant flow.
  4. The MCP server sends the user’s token as subject token and its actor token to the Cognito /oauth2/token endpoint in a delegation token exchange. It requests only email-api/messages.send, because sending invites doesn’t require reading your contacts.
    curl -X POST "https://<domain>.auth.us-east-1.amazoncognito.com/oauth2/token" \
      -u "$MCP_SERVER_CLIENT_ID:$MCP_SERVER_CLIENT_SECRET" \
      -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
      --data-urlencode "subject_token=$YOUR_TOKEN" \
      -d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
      --data-urlencode "actor_token=$ACTOR_TOKEN" \
      -d actor_token_type=urn:ietf:params:oauth:token-type:access_token \
      -d audience=email-api \
      -d scope=email-api/messages.send
  5. Cognito validates both tokens and returns the issued token, while keeping the user in sub claim and adding the MCP server’s app client to act claim.
    {
      "sub": "c4b82478-...",
      "username": "you@example.com",
      "client_id": "<MCP server app client ID>",
      "aud": "email-api",
      "scope": "email-api/messages.send",
      "act": {
        "sub": "<MCP server app client ID>",
        "client_id": "<MCP server app client ID>",
        "iss": "https://cognito-idp.us-east-1.amazonaws.com/<user-pool-id>",
        "token_type": "urn:ietf:params:oauth:token-type:access_token"
      },
      "token_use": "access"
    }
  6. The MCP server calls the email API with the issued token. The email API checks aud=email-api and the messages.send scope, and it confirms that act.client_id matches client_id and names an MCP server it trusts. It then sends the invites from your account and records that the invitations MCP server sent them for you.

To set up the MCP server:

  1. In Amazon Cognito user pool, register the email API (email-api) and the MCP server (invitations-mcp) as resource servers in your user pool, with the scopes used.
  2. Create an app client with a client secret for the MCP server in your user pool. Select ALLOW_TOKEN_EXCHANGE_DELEGATION in authentication flows, allow the client credentials grant so the MCP server can get its actor token, and allow the email-api/messages.send scope that it requests in the exchange.
  3. Have the review app request email-api/messages.send when you sign in, along with invitations-mcp/tools. The exchange can remove scopes from your token, but it can’t add any.

Other AI agents can also sign you in through Amazon Cognito and call the invitations MCP server. They can register with your user pool through dynamic client registration (DCR), or identify themselves with a client ID metadata document (CIMD). Token exchange works the same way for these clients. They send your access token to the MCP server, and the MCP server performs the exchange with its own app client, so the issued token names you in sub and the MCP server in act.

Using AgentCore Gateway:

If you don’t want to write the exchange in your MCP server, AgentCore Gateway can perform it for you. Amazon Bedrock AgentCore Identity can perform the same token exchange on behalf of AgentCore Gateway, so the gateway doesn’t store the OAuth client secret or build the request.

Here, AgentCore Gateway replaces the invitations MCP server. It exposes the email API as an MCP tool through an OpenAPI target, and the review app’s AI agent calls that tool with your access token.

Figure 6 shows how AgentCore Gateway sends invites for you.

Figure 6: AgentCore Gateway sending invites through AgentCore Identity

Figure 6: AgentCore Gateway sending invites through AgentCore Identity

  1. The agent calls the AgentCore Gateway invite tool with user’s access token. The AgentCore Gateway inbound JWT authorizer validates the token against your user pool and accepts only tokens issued to the review app.
  2. AgentCore Gateway passes user’s access token to AgentCore Identity and asks for a token for the email API target.
  3. AgentCore Identity uses the AgentCore Gateway app client in a client credentials grant to get an actor token.
  4. AgentCore Identity sends your token and the actor token in a delegation token exchange, adding the subject_token_type and audience values from the target’s custom parameters.
  5. Amazon Cognito validates the request and returns the issued token, with the user in sub, and the AgentCore Gateway app client in act.
  6. AgentCore Identity passes the issued token to AgentCore Gateway.
  7. AgentCore Gateway calls the email API with the issued token, and the email API applies the same checks as for the preceding MCP server setup.

To set up AgentCore Gateway:

  1. In your Amazon Cognito user pool, create an app client for AgentCore Gateway in the same way as for the MCP server.
  2. In AgentCore Identity, create an AgentCore Identity credential provider for the AgentCore Gateway app client. A credential provider stores what AgentCore Identity needs to request tokens from Amazon Cognito: your user pool’s discovery URL and the app client’s ID and secret. Use the CustomOauth2 provider type, and enable delegation in its customOauth2ProviderConfig settings:
    {
      "oauthDiscovery": { "discoveryUrl": "https://cognito-idp.us-east-1.amazonaws.com/<user-pool-id>/.well-known/openid-configuration" },
      "clientId": "<Gateway app client ID>",
      "clientSecret": "<client secret>",
      "clientAuthenticationMethod": "CLIENT_SECRET_BASIC",
      "onBehalfOfTokenExchangeConfig": {
        "grantType": "TOKEN_EXCHANGE",
        "tokenExchangeGrantTypeConfig": { "actorTokenContent": "M2M" }
      }
    }
  3. In AgentCore Gateway, configure the AgentCore Gateway inbound JWT authorizer with your user pool’s discovery URL, and set allowedClients to the review app’s client ID.
  4. In the AgentCore Gateway target’s outbound authorization, reference the credential provider and add subject_token_type and audience as custom parameters. Because your token is an access token, set subject_token_type to urn:ietf:params:oauth:token-type:access_token.
    {
      "providerArn": "arn:aws:bedrock-agentcore:us-east-1:<account-id>:token-vault/default/oauth2credentialprovider/cognito",
      "scopes": ["email-api/messages.send"],
      "grantType": "TOKEN_EXCHANGE",
      "customParameters": {
        "subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
        "audience": "email-api"
      }
    }

AgentCore Gateway handles the exchange through configuration, so you don’t need to write agent or interceptor code for it. For more information, see Set up outbound authorization for your gateway.

With either your own MCP server or an AI gateway, act names the intermediary rather than the agent that called it. Every agent behind it appears as the same app client. This design still protects the email API. It accepts only tokens with aud=email-api, and your original access token has no such audience, so an agent can’t bypass the intermediary by forwarding your token. Each call that reaches the email API carries a token with only the scope it needs. The agents don’t hold downstream credentials or exchange logic, and the email API trusts one intermediary instead of every agent. If the email API needs to tell agents apart, perform the exchange in the agent, as Example 2 shows.

Example 2: The agent as the actor on AgentCore Runtime

If the review app’s AI agent runs on Amazon Bedrock AgentCore Runtime, the agent can request the exchange itself through AgentCore Identity and call the email API directly. The issued token then names the agent in act, so the email API knows which agent sent the invites.

Figure 7 shows how the agent sends invites for you.

Figure 7: The AI agent on AgentCore Runtime sending invites through AgentCore Identity

Figure 7: The AI agent on AgentCore Runtime sending invites through AgentCore Identity

  1. The review app invokes the agent on AgentCore Runtime with the user’s access token.
  2. Runtime validates your token with its inbound JWT authorizer, exchanges it for a workload access token from AgentCore Identity, and passes that token to the agent. A workload access token is an opaque token that proves which agent is calling. It carries the user’s access token, which AgentCore Identity uses as the subject token in step 4.
  3. The agent asks AgentCore Identity for a token for the email API by calling GetResourceOauth2Token with the workload access token.
  4. AgentCore Identity gets an actor token with the agent’s app client, then sends user’s token and the actor token to Cognito in a delegation token exchange.
  5. Amazon Cognito returns the issued token, with user in sub and the agent’s app client in act, and AgentCore Identity passes it to the agent.
  6. The agent calls the email API with the issued token. The email API applies the same checks as in Example 1, and confirms that act.client_id names an agent it trusts.

The issued token has the same shape as in Example 1, but client_id and act name the agent’s app client.

To set up the agent:

  1. In your Amazon Cognito user pool, create an app client for the agent in your user pool and select ALLOW_TOKEN_EXCHANGE_DELEGATION for it. To tell agents apart in act claim, give each agent its own app client and credential provider.
  2. In AgentCore Identity, create a credential provider for the agent’s app client in the same way as for AgentCore Gateway.
  3. In AgentCore Runtime, configure the inbound JWT authorizer on AgentCore Runtime to accept your user pool’s tokens, with allowedClients set to the review app’s client ID.
  4. In the agent’s code, request the issued token with the AgentCore SDK:
    from bedrock_agentcore.identity.auth import requires_access_token
    
    @requires_access_token(
        provider_name="<Agent name>",
        scopes=["email-api/messages.send"],
        audiences=["email-api"],
        auth_flow="ON_BEHALF_OF_TOKEN_EXCHANGE",
        custom_parameters={
            "subject_token_type": "urn:ietf:params:oauth:token-type:access_token"
        },
    )
    async def send_invites(friends: list[str], *, access_token: str):
        # Call the email API with access_token
        ...

The decorator makes the GetResourceOauth2Token call in step 3 of Figure 7 and passes the issued token to your function as access_token.

For more information, see On-behalf-of token exchange with AgentCore Identity.

Conclusion

Think back to the agent at the start of this post. The agent had to book a table and send invitations for you, and forwarding the user’s original access token would have hidden which service acted for you and given it more access than the job needed. With Amazon Cognito token exchange, each hop gets its own scoped-down token, bound to the resource server it calls and limited to the scopes it needs. Each issued token also expires no later than your own token and doesn’t come with a refresh token, so no service can keep access after your token expires.

For AI agents, delegation adds a second identity to the token. The act claim names the service doing the work, so a downstream API can choose which agents it trusts. Your audit records can then show both the person who authorized a request and the agent that made it.

You can try this on a new or existing Amazon Cognito user pool on the Essentials or Plus plan. Enable ALLOW_TOKEN_EXCHANGE_DELEGATION for an app client, register the downstream API as a resource server, and call GetDerivedToken or the token endpoint.

If you have questions about this post, contact AWS Support or start a new thread on AWS re:Post.


Edward Sun

Edward Sun

Edward is a Senior Security Specialist Solutions Architect focused on identity and access management. He loves helping customers throughout their cloud transformation journey with architecture design, security best practices, migration, and cost optimizations. Outside of work, Edward enjoys hiking, golfing, and cheering for his alma mater, the Georgia Bulldogs.

Owen Hawkins

Owen is a Principal Solutions Architect at Amazon Web Services, working with independent software vendors in the UK. Building on more than 20 years in information security and digital banking, he now spends his time on agent identity and on helping engineering organizations improve their software development lifecycle with AI-driven approaches.

Varun Sharma

Varun is a Senior AWS Cloud Security Engineer who wears his security cape proudly. With a knack for unravelling the mysteries of Amazon Cognito and IAM, Varun is a go-to subject matter expert for these services. When he’s not busy securing the cloud, you’ll find him in the world of security penetration testing. And when the pixels are at rest, Varun switches gears to capture the beauty of nature through the lens of his camera.