Cognito token exchange lets a service trade a user's token for a new, narrower one, and I have been waiting for exactly that ever since AI agents started showing up in every project I look at. Sooner or later, every architecture discussion about agents hits the same question: “Which token does the agent actually use to call the backend API?” So far, the honest answer was often: the user's token, simply passed along. That works, but it's a bit like handing the delivery driver your house key so they can drop a parcel in the hallway.

Since November 12, 2026, Amazon Cognito can exchange tokens according to the OAuth standard RFC 8693. In this article, we build a complete example: a bookstore AI agent reads a customer's orders with a token that can only read, only works for the orders API and reveals the agent. The infrastructure uses AWS CDK, the code TypeScript.

In short

Cognito token exchange swaps a user's token for a new token that can do less, is only valid for one specific service and comes without a refresh token. If you add an actor token, the new token contains an act claim, so the backend API can tell that an agent is acting on the user's behalf. However, there is a catch right now: neither the AWS SDKs nor the CloudFormation schema know the new feature yet. Luckily, the token endpoint and a small script get you around both.

What you will learn in this article

  • What token exchange is and when impersonation or delegation fits
  • How to give an AI agent a tightly scoped token for exactly one API
  • How the backend API uses the act claim to recognize an agent
  • Building all of it with AWS CDK, TypeScript and Vitest
  • Which pitfalls you will hit at launch

What is Cognito token exchange?

Token exchange is an extension of OAuth 2.0. A service presents an existing token and receives a new one in return. The token you present is called the subject token: it represents the person on whose behalf the service acts. Optionally, you add an actor token that identifies the acting service itself, for example an agent or an MCP server.

A few terms first, so beginners can follow along. An access token is a signed JSON Web Token (JWT) that an API checks on every call. Scopes describe what the token may do, for example bestellungen/lesen (German for “orders/read”). The audience (the aud claim) says which recipient the token is meant for. In Cognito, an audience corresponds to a resource server, which is an API you register in your user pool and for which you define your own scopes.

Cognito token exchange connects these building blocks: the new token gets a single audience, at most the scopes the original already had, and no refresh token. You trigger the exchange via the token endpoint /oauth2/token or the new API operation GetDerivedToken. You need a user pool on the Essentials or Plus plan; Lite doesn't include it.

Why passing the user token along is a problem

Picture a chat assistant in an online bookstore. The customer asks: “Where is my order?” To answer, the agent needs data from the orders API. The convenient way: it takes the access token the customer used to call the chat and forwards it unchanged.

However, that gets you several problems at once. First, the token is too powerful, because it might also be allowed to cancel orders while the agent should only read. Besides, it was never issued for the orders API, but for the chat application. Finally, the orders API can't tell whether the customer clicked herself or a language model just decided to do something. For audit logs, liability questions and plain debugging, that is a blind spot.

The alternative so far was to sign your own tokens: your own key, your own rotation, your own code that assembles claims. That works, but it is exactly the kind of security code I would rather not maintain myself. With Cognito token exchange, the user pool takes over this job, and the backend API validates the new token like any other Cognito token.

Impersonation or delegation in token exchange

Cognito offers two variants. Which one you get depends solely on whether you send an actor token with the exchange.

Variant Actor token What the new token contains Good fit for
Impersonation no The token looks as if the user acted directly, without an act claim your own backend services that just need a narrower token
Delegation yes Additionally an act claim with the identity of the intermediary AI agents, MCP servers and anything you want to see separately in the audit log

For AI agents, I almost always choose delegation. The extra effort is a second token. In return, the API always knows who really acted. Impersonation is handy when, for example, the shop's backend calls an internal API and the distinction doesn't matter.

You enable the variants per app client with the auth flows ALLOW_TOKEN_EXCHANGE_IMPERSONATION and ALLOW_TOKEN_EXCHANGE_DELEGATION. Of course, a client may also have both.

What Cognito guarantees during the exchange

The security promises are the real reason I like this feature. According to the developer guide:

  • Only narrow, never widen: The scopes in the new token are the intersection of the requested scopes, the scopes of the subject token and the scopes the exchanging app client is allowed to grant at all.
  • No refresh token: The exchanged token expires on its own. Once the customer's session ends, nobody can mint new tokens from it.
  • The original is checked: Cognito verifies the signature, expiry and revocation status of the subject token, for example after a global sign-out. Disabled or unconfirmed users don't get a token.
  • One audience: The new token is valid for exactly one registered resource server.

There are two limits you should know. Cognito doesn't evaluate the may_act claim from RFC 8693. As a result, you can't declare in the original token up front which agents may act. You have to implement that rule yourself, for example via the agent client's scopes or a Lambda trigger. Also, token exchange doesn't create users: if the subject token comes from an external identity provider, the user must already be linked in the user pool.

The example: a bookstore agent reads orders

Our fictional bookstore has three building blocks. The web app signs the customer in via Cognito and uses that token to call the agent API. Next, the agent Lambda exchanges the token and calls the orders API on her behalf. Finally, the orders API only accepts tokens with the audience bestellungen and writes to its log whether an agent was involved.

Cognito token exchange diagram: the agent exchanges the customer token and calls the orders API with aud and act claim

Delegation in the example: only the exchanged token with the audience “bestellungen” gets through the orders API.

One detail completes the pattern: Cognito access tokens from a normal sign-in contain no aud claim, only the client_id of the web app. The API Gateway JWT authorizer compares the configured audience with aud or, if that is missing, with client_id. If you set the orders API to the audience bestellungen, it rejects the customer's original token. Only tokens that went through the exchange get in.

Prerequisites

  • An AWS account and the AWS CLI with valid credentials
  • Node.js 22 or newer (I tested with Node.js 24)
  • AWS CDK v2 and a bootstrapped account (npx cdk bootstrap)
  • curl, jq and openssl for the test at the end
  • Basic knowledge of OAuth 2.0 and JWT helps, but isn't a must

Step by step: Cognito token exchange with AWS CDK

Step 1: Create the project

Create an empty directory and install the packages. The project uses ES modules and TypeScript 7.

mkdir bookstore-token-exchange && cd bookstore-token-exchange npm init -y && npm pkg set type=module npm install @aws-sdk/client-cognito-identity-provider npm install -D aws-cdk aws-cdk-lib constructs typescript tsx esbuild vitest @types/node @types/aws-lambda mkdir bin lib src scripts test 

The files tsconfig.json, cdk.json and bin/app.ts are standard. You can find them in the example repository linked at the end.

Step 2: User pool, resource servers and app clients

The stack creates a user pool on the Essentials plan, two resource servers and two app clients. The web client is public and uses the authorization code flow with PKCE. In addition, the agent client gets a secret and the client credentials flow, so it can identify itself with its own token. Its scope bestellungen/lesen therefore acts as an upper limit: the agent can never get more through the exchange, no matter what the customer is allowed to do.

// lib/token-exchange-stack.ts import { fileURLToPath } from 'node:url'; import { CfnOutput, Duration, RemovalPolicy, Stack, type StackProps } from 'aws-cdk-lib'; import type { Construct } from 'constructs'; import * as cognito from 'aws-cdk-lib/aws-cognito'; import * as iam from 'aws-cdk-lib/aws-iam'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; import { HttpApi, HttpMethod } from 'aws-cdk-lib/aws-apigatewayv2'; import { HttpJwtAuthorizer } from 'aws-cdk-lib/aws-apigatewayv2-authorizers'; import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations'; const src = (file: string) => fileURLToPath(new URL(`../src/${file}`, import.meta.url)); const fn = (scope: Construct, id: string, file: string, environment?: Record<string, string>) => new nodejs.NodejsFunction(scope, id, { entry: src(file), runtime: lambda.Runtime.NODEJS_24_X, architecture: lambda.Architecture.ARM_64, timeout: Duration.seconds(10), environment, }); export class TokenExchangeStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); // 1. User pool on the Essentials plan (required for token exchange) const pool = new cognito.UserPool(this, 'Kunden', { featurePlan: cognito.FeaturePlan.ESSENTIALS, signInAliases: { email: true }, selfSignUpEnabled: false, customAttributes: { ki_freigabe: new cognito.StringAttribute({ mutable: true }) }, removalPolicy: RemovalPolicy.DESTROY, }); pool.addTrigger( cognito.UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG, fn(this, 'PreToken', 'pre-token.ts'), cognito.LambdaVersion.V2_0, ); const domain = pool.addDomain('Domain', { cognitoDomain: { domainPrefix: `buchladen-agent-${this.account}` }, }); // 2. Resource servers: the orders API and the agent itself const lesen = new cognito.ResourceServerScope({ scopeName: 'lesen', scopeDescription: 'Read orders' }); const stornieren = new cognito.ResourceServerScope({ scopeName: 'stornieren', scopeDescription: 'Cancel orders' }); const bestellungen = pool.addResourceServer('Bestellungen', { identifier: 'bestellungen', scopes: [lesen, stornieren] }); const chat = new cognito.ResourceServerScope({ scopeName: 'chat', scopeDescription: 'Talk to the agent' }); const handeln = new cognito.ResourceServerScope({ scopeName: 'handeln', scopeDescription: 'Agent identifies itself' }); const agentServer = pool.addResourceServer('Agent', { identifier: 'buchladen-agent', scopes: [chat, handeln] }); // 3. App client of the web app (public, authorization code with PKCE) const webClient = pool.addClient('WebApp', { generateSecret: false, oAuth: { flows: { authorizationCodeGrant: true }, callbackUrls: ['http://localhost:5173/callback'], scopes: [ cognito.OAuthScope.OPENID, cognito.OAuthScope.resourceServer(agentServer, chat), cognito.OAuthScope.resourceServer(bestellungen, lesen), cognito.OAuthScope.resourceServer(bestellungen, stornieren), ], }, }); // 4. App client of the agent: client credentials (actor token) + token exchange via delegation const agentClient = pool.addClient('AgentClient', { generateSecret: true, oAuth: { flows: { clientCredentials: true }, scopes: [ cognito.OAuthScope.resourceServer(agentServer, handeln), cognito.OAuthScope.resourceServer(bestellungen, lesen), // upper limit for exchanged tokens ], }, }); // The CloudFormation schema doesn't know ALLOW_TOKEN_EXCHANGE_DELEGATION yet (as of 11/13/2026). // That's why scripts/enable-token-exchange.ts sets the flow after the deployment. const issuer = `https://cognito-idp.${this.region}.amazonaws.com/${pool.userPoolId}`; // 5. Orders API: only accepts tokens with aud = "bestellungen" const ordersApi = new HttpApi(this, 'BestellApi'); const ordersAuth = new HttpJwtAuthorizer('BestellAuth', issuer, { jwtAudience: ['bestellungen'] }); const ordersFn = fn(this, 'BestellFn', 'orders-api.ts'); ordersApi.addRoutes({ path: '/bestellungen', methods: [HttpMethod.GET], integration: new HttpLambdaIntegration('BestellLesen', ordersFn), authorizer: ordersAuth, authorizationScopes: ['bestellungen/lesen'], }); ordersApi.addRoutes({ path: '/bestellungen/{id}', methods: [HttpMethod.DELETE], integration: new HttpLambdaIntegration('BestellStornieren', ordersFn), authorizer: ordersAuth, authorizationScopes: ['bestellungen/stornieren'], }); // 6. Agent API: accepts web app tokens with the scope buchladen-agent/chat const agentFn = fn(this, 'AgentFn', 'agent.ts', { USER_POOL_ID: pool.userPoolId, AGENT_CLIENT_ID: agentClient.userPoolClientId, TOKEN_URL: `${domain.baseUrl()}/oauth2/token`, ORDERS_API_URL: ordersApi.apiEndpoint, }); agentFn.addToRolePolicy(new iam.PolicyStatement({ actions: ['cognito-idp:DescribeUserPoolClient'], resources: [pool.userPoolArn], })); const agentApi = new HttpApi(this, 'AgentApi'); agentApi.addRoutes({ path: '/agent/bestellungen', methods: [HttpMethod.GET], integration: new HttpLambdaIntegration('AgentIntegration', agentFn), authorizer: new HttpJwtAuthorizer('AgentAuth', issuer, { jwtAudience: [webClient.userPoolClientId] }), authorizationScopes: ['buchladen-agent/chat'], }); new CfnOutput(this, 'UserPoolId', { value: pool.userPoolId }); new CfnOutput(this, 'AgentClientId', { value: agentClient.userPoolClientId }); new CfnOutput(this, 'WebClientId', { value: webClient.userPoolClientId }); new CfnOutput(this, 'HostedUi', { value: domain.baseUrl() }); new CfnOutput(this, 'AgentApiUrl', { value: agentApi.apiEndpoint }); } } 

In theory, the agent client could fetch a token with bestellungen/lesen on its own via client credentials. However, that token would have no aud claim and the agent's ID as client_id. That's why the orders API rejects it. Without the exchange, and therefore without the customer, the agent can't reach the orders.

Step 3: Enable the token exchange flow after deployment

Here comes the first pitfall. Ideally, I would set ALLOW_TOKEN_EXCHANGE_DELEGATION directly in the stack. With aws-cdk-lib 2.276.0, however, cdk synth reports warning W3030 for it: the bundled CloudFormation schema only knows the previous values. So I removed the value from the stack and set it with a script after the deployment.

A second trap is waiting there. UpdateUserPoolClient resets every field you don't send to its default value. If you only pass the auth flows, you lose scopes and OAuth settings. That's why the helper function reads the current configuration first and only adds the new flow:

// src/client-update.ts // Builds a complete UpdateUserPoolClient request from DescribeUserPoolClient. // Important: UpdateUserPoolClient resets every field you don't send to its default value. import type { UpdateUserPoolClientCommandInput, UserPoolClientType } from '@aws-sdk/client-cognito-identity-provider'; const NICHT_AKTUALISIERBAR = ['ClientSecret', 'CreationDate', 'LastModifiedDate'] as const; export function withAuthFlow(client: UserPoolClientType, flow: string): UpdateUserPoolClientCommandInput { const input: Record<string, unknown> = { ...client }; for (const key of NICHT_AKTUALISIERBAR) delete input[key]; const flows = new Set<string>(client.ExplicitAuthFlows ?? []); flows.add(flow); // The SDK doesn't know the new value as a type yet, but sends it unchanged input.ExplicitAuthFlows = [...flows]; return input as unknown as UpdateUserPoolClientCommandInput; } 
// scripts/enable-token-exchange.ts // Usage: npx tsx scripts/enable-token-exchange.ts <user-pool-id> <agent-client-id> import { CognitoIdentityProviderClient, DescribeUserPoolClientCommand, UpdateUserPoolClientCommand, } from '@aws-sdk/client-cognito-identity-provider'; import { withAuthFlow } from '../src/client-update.js'; const [userPoolId, clientId] = process.argv.slice(2); if (!userPoolId || !clientId) { console.error('Usage: npx tsx scripts/enable-token-exchange.ts <user-pool-id> <agent-client-id>'); process.exit(1); } const cognito = new CognitoIdentityProviderClient({}); const { UserPoolClient } = await cognito.send(new DescribeUserPoolClientCommand({ UserPoolId: userPoolId, ClientId: clientId })); const input = withAuthFlow(UserPoolClient!, 'ALLOW_TOKEN_EXCHANGE_DELEGATION'); await cognito.send(new UpdateUserPoolClientCommand(input)); console.log('Auth flows now:', input.ExplicitAuthFlows?.join(', ')); 

Keep in mind: a later cdk deploy that changes the agent client can remove the flow again. Run the script in your pipeline after every deployment until CloudFormation knows the value. After that, it belongs back in the stack.

Step 4: Call the token endpoint

Second pitfall: @aws-sdk/client-cognito-identity-provider 3.1168.0, the current version from November 12, has no GetDerivedTokenCommand yet. botocore 1.44.2 doesn't know the operation either. That's no big deal, because the token endpoint speaks standard OAuth. A few lines of fetch are enough:

// src/token-client.ts // Small client for the Cognito token endpoint: client credentials and token exchange (RFC 8693) export const GRANT_TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange'; export const TYPE_ACCESS_TOKEN = 'urn:ietf:params:oauth:token-type:access_token'; export interface ClientConfig { tokenUrl: string; // https://<prefix>.auth.<region>.amazoncognito.com/oauth2/token clientId: string; clientSecret: string; } export interface TokenResponse { access_token: string; token_type: string; expires_in: number; issued_token_type?: string; } export interface ExchangeRequest { subjectToken: string; // the user's access token actorToken?: string; // the agent's token -> act claim (delegation) audience: string; // resource server, e.g. "bestellungen" scopes: string[]; // requested, narrower scopes<...
Source:https://dev.to/sascha-ms/cognito-token-exchange-let-ai-agents-act-safely-c78