DEV Community

Cover image for Cognito token exchange: let AI agents act safely
Sascha Mirow-Stanitzok
Sascha Mirow-Stanitzok

Posted on Originally published at sascha-ms.de

Cognito token exchange: let AI agents act safely

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
Enter fullscreen mode Exit fullscreen mode

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 });
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode
// 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(', '));
Enter fullscreen mode Exit fullscreen mode

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
}

export function buildExchangeBody(req: ExchangeRequest): URLSearchParams {
  if (req.scopes.length === 0) throw new Error('Specify at least one scope');
  const body = new URLSearchParams({
    grant_type: GRANT_TOKEN_EXCHANGE,
    subject_token: req.subjectToken,
    subject_token_type: TYPE_ACCESS_TOKEN,
    audience: req.audience,
    scope: req.scopes.join(' '),
  });
  if (req.actorToken) {
    body.set('actor_token', req.actorToken);
    body.set('actor_token_type', TYPE_ACCESS_TOKEN);
  }
  return body;
}

export function buildClientCredentialsBody(scopes: string[]): URLSearchParams {
  return new URLSearchParams({ grant_type: 'client_credentials', scope: scopes.join(' ') });
}

function basicAuth(cfg: ClientConfig): string {
  return 'Basic ' + Buffer.from(`${cfg.clientId}:${cfg.clientSecret}`).toString('base64');
}

export async function requestToken(cfg: ClientConfig, body: URLSearchParams): Promise<TokenResponse> {
  const res = await fetch(cfg.tokenUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: basicAuth(cfg),
    },
    body,
  });
  const json = (await res.json()) as TokenResponse & { error?: string };
  if (!res.ok) {
    // pass on the error without any token contents
    throw new Error(`Token endpoint returned ${res.status}: ${json.error ?? 'unknown error'}`);
  }
  return json;
}

// Read the payload of a JWT WITHOUT checking the signature.
// Only use this when an authorizer (e.g. the API Gateway JWT authorizer) has already verified it.
export function decodeJwtPayload(jwt: string): Record<string, unknown> {
  const parts = jwt.split('.');
  if (parts.length !== 3) throw new Error('Not a valid JWT');
  return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
}
Enter fullscreen mode Exit fullscreen mode

The parameters have exactly the names from RFC 8693: subject_token for the customer token, actor_token for the agent token and audience for the resource server. For the token endpoint, the user pool needs a domain, which the stack already creates in step 2.

Step 5: The agent exchanges the token

On a cold start, the agent Lambda fetches its client secret via DescribeUserPoolClient instead of storing it in an environment variable. It also caches the actor token from client credentials until shortly before it expires. That saves calls, and Cognito bills M2M tokens separately.

// src/agent.ts
// Agent Lambda: accepts the user token, exchanges it and calls the orders API on the user's behalf
import type { APIGatewayProxyEventV2WithJWTAuthorizer, APIGatewayProxyResultV2 } from 'aws-lambda';
import { CognitoIdentityProviderClient, DescribeUserPoolClientCommand } from '@aws-sdk/client-cognito-identity-provider';
import { buildClientCredentialsBody, buildExchangeBody, requestToken, type ClientConfig } from './token-client.js';

const cognito = new CognitoIdentityProviderClient({});
const { USER_POOL_ID, AGENT_CLIENT_ID, TOKEN_URL, ORDERS_API_URL } = process.env as Record<string, string>;

let config: ClientConfig | undefined;
let actor: { token: string; validUntil: number } | undefined;

// Fetch the client secret once per cold start instead of storing it in environment variables
async function getConfig(): Promise<ClientConfig> {
  if (config) return config;
  const out = await cognito.send(new DescribeUserPoolClientCommand({ UserPoolId: USER_POOL_ID, ClientId: AGENT_CLIENT_ID }));
  config = { tokenUrl: TOKEN_URL, clientId: AGENT_CLIENT_ID, clientSecret: out.UserPoolClient!.ClientSecret! };
  return config;
}

// The agent's actor token (client credentials), cached until shortly before it expires
async function getActorToken(cfg: ClientConfig): Promise<string> {
  if (actor && actor.validUntil > Date.now()) return actor.token;
  const res = await requestToken(cfg, buildClientCredentialsBody(['buchladen-agent/handeln']));
  actor = { token: res.access_token, validUntil: Date.now() + (res.expires_in - 60) * 1000 };
  return actor.token;
}

export const handler = async (event: APIGatewayProxyEventV2WithJWTAuthorizer): Promise<APIGatewayProxyResultV2> => {
  const userToken = (event.headers.authorization ?? '').replace(/^Bearer\s+/i, '');
  const cfg = await getConfig();

  // Delegation: user token + actor token -> new token only for the orders API, read only
  const exchanged = await requestToken(
    cfg,
    buildExchangeBody({
      subjectToken: userToken,
      actorToken: await getActorToken(cfg),
      audience: 'bestellungen',
      scopes: ['bestellungen/lesen'],
    }),
  );

  const res = await fetch(`${ORDERS_API_URL}/bestellungen`, {
    headers: { Authorization: `Bearer ${exchanged.access_token}` },
  });
  const bestellungen = await res.json();

  // A real agent would pass the data to the language model here
  return { statusCode: 200, body: JSON.stringify({ antwort: 'Your latest orders', bestellungen }) };
};
Enter fullscreen mode Exit fullscreen mode

In a real agent, this code lives in the tool the language model calls, for example in a tool handler of your MCP server. I show how to run an MCP server on Lambda in the article MCP server on Lambda.

🎬 Flow of a token exchange with delegation – this animated diagram only runs on my site: watch it on sascha-ms.de

Step 6: The orders API evaluates the act claim

API Gateway checks signature, expiry, audience and scope. The Lambda behind it then decides what an agent may do. To keep that easy to test, the rule lives in its own function:

// src/policy.ts
// Decides in the orders API what a call may do, depending on whether an agent is involved

export type Aktion = 'lesen' | 'stornieren';

export interface Entscheidung {
  erlaubt: boolean;
  grund: string;
  akteur?: string; // client ID of the agent from the act claim
}

export function entscheide(claims: Record<string, unknown>, aktion: Aktion): Entscheidung {
  const scopes = String(claims.scope ?? '').split(' ');
  const act = claims.act as { sub?: string } | undefined;
  const akteur = act?.sub;

  if (!scopes.includes(`bestellungen/${aktion}`)) {
    return { erlaubt: false, grund: `Scope bestellungen/${aktion} is missing`, akteur };
  }
  // An agent may never cancel, even if a scope slips through
  if (akteur && aktion === 'stornieren') {
    return { erlaubt: false, grund: 'Only the person themselves may cancel', akteur };
  }
  return { erlaubt: true, grund: akteur ? `on behalf via ${akteur}` : 'direct', akteur };
}
Enter fullscreen mode Exit fullscreen mode
// src/orders-api.ts
// Orders API: API Gateway checks signature, aud and scope; the Lambda also checks the act claim
import type { APIGatewayProxyEventV2WithJWTAuthorizer, APIGatewayProxyResultV2 } from 'aws-lambda';
import { decodeJwtPayload } from './token-client.js';
import { entscheide } from './policy.js';

const BEISPIEL = [
  { id: 'B-1001', titel: 'The Hobbit', status: 'shipped' },
  { id: 'B-1002', titel: 'Cooking for Geeks', status: 'processing' },
];

export const handler = async (event: APIGatewayProxyEventV2WithJWTAuthorizer): Promise<APIGatewayProxyResultV2> => {
  const token = (event.headers.authorization ?? '').replace(/^Bearer\s+/i, '');
  const claims = decodeJwtPayload(token); // the JWT authorizer has already checked the signature
  const aktion = event.requestContext.http.method === 'DELETE' ? 'stornieren' : 'lesen';
  const e = entscheide(claims, aktion);

  // Audit log: who acted, and was an agent involved?
  console.log(JSON.stringify({ nutzer: claims.sub, akteur: e.akteur ?? null, aktion, erlaubt: e.erlaubt }));

  if (!e.erlaubt) return { statusCode: 403, body: JSON.stringify({ fehler: e.grund }) };
  if (aktion === 'stornieren') return { statusCode: 204 };
  return { statusCode: 200, body: JSON.stringify(BEISPIEL) };
};
Enter fullscreen mode Exit fullscreen mode

Note that the Lambda reads the payload without its own signature check. That's fine here, because the route can't be reached without passing the JWT authorizer. If you also call the Lambda from other sources, verify the signature yourself, for example with the aws-jwt-verify library.

Moreover, the cancel route shows the difference between the two variants. If the customer wants to cancel herself, the shop's backend could get a token with bestellungen/stornieren via impersonation, so without an act claim. The agent, on the other hand, never gets that scope. Even if it slipped through, the policy blocks every call that carries an act claim.

Step 7: Opt-in via the pre token generation trigger

People should decide for themselves whether an agent may act for them. During the exchange, Cognito invokes the pre token generation trigger with the source TokenGeneration_TokenExchange. If the function throws an error, the exchange fails. I use that as an opt-in via the attribute custom:ki_freigabe (German for “AI consent”):

// src/pre-token.ts
// Pre token generation trigger: token exchange only for users who allowed AI access
import type { PreTokenGenerationV2TriggerEvent } from 'aws-lambda';

export const handler = async (event: PreTokenGenerationV2TriggerEvent) => {
  // The string comes from the Cognito docs; the aws-lambda types don't know it yet
  const quelle: string = event.triggerSource;
  if (quelle === 'TokenGeneration_TokenExchange') {
    if (event.request.userAttributes['custom:ki_freigabe'] !== 'ja') {
      throw new Error('AI access is not enabled for this account');
    }
  }
  return event;
};
Enter fullscreen mode Exit fullscreen mode

The trigger receives the user's attributes, but not the raw tokens. It can't add scopes during an exchange, only change claims, suppress scopes or deny the request.

Step 8: Test, deploy, try it out

The policy and the token helpers are pure functions and can be tested without AWS. An excerpt from the Vitest tests:

// test/policy.test.ts
import { describe, expect, it } from 'vitest';
import { entscheide } from '../src/policy.js';

describe('entscheide', () => {
  it('lets the agent read and records the actor', () => {
    const e = entscheide({ sub: 'u1', scope: 'bestellungen/lesen', act: { sub: 'agent-1' } }, 'lesen');
    expect(e).toEqual({ erlaubt: true, grund: 'on behalf via agent-1', akteur: 'agent-1' });
  });

  it('does not let the agent cancel, even with the scope', () => {
    const e = entscheide({ scope: 'bestellungen/lesen bestellungen/stornieren', act: { sub: 'agent-1' } }, 'stornieren');
    expect(e.erlaubt).toBe(false);
  });

  it('lets the person cancel themselves', () => {
    expect(entscheide({ scope: 'bestellungen/stornieren' }, 'stornieren').erlaubt).toBe(true);
  });

  it('denies when the scope is missing', () => {
    expect(entscheide({ scope: 'buchladen-agent/chat' }, 'lesen').grund).toMatch(/Scope/);
  });
});
Enter fullscreen mode Exit fullscreen mode
npx tsc --noEmit
npx vitest run
npx cdk deploy
Enter fullscreen mode Exit fullscreen mode

After the deployment, enable the flow and create a test customer. You'll find the IDs in the stack outputs.

npx tsx scripts/enable-token-exchange.ts <UserPoolId> <AgentClientId>

aws cognito-idp admin-create-user --user-pool-id <UserPoolId> \
  --username anna@example.com --message-action SUPPRESS \
  --user-attributes Name=email,Value=anna@example.com Name=email_verified,Value=true Name=custom:ki_freigabe,Value=ja
aws cognito-idp admin-set-user-password --user-pool-id <UserPoolId> \
  --username anna@example.com --password 'A-long-test-password-42!' --permanent
Enter fullscreen mode Exit fullscreen mode

To get a token with custom scopes, there is no way around the OAuth sign-in. With PKCE, that works without a frontend too: open the printed URL in your browser and sign in. Your browser can't load the localhost redirect, but the address bar still shows the code parameter.

HOSTED_UI=<HostedUi>; WEB_CLIENT_ID=<WebClientId>; REDIRECT=http://localhost:5173/callback
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n' | cut -c1-64)
CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=')
echo "$HOSTED_UI/oauth2/authorize?response_type=code&client_id=$WEB_CLIENT_ID&redirect_uri=$REDIRECT&scope=openid+buchladen-agent/chat+bestellungen/lesen&code_challenge_method=S256&code_challenge=$CHALLENGE"

CODE=<code from the address bar>
TOKEN=$(curl -s -X POST "$HOSTED_UI/oauth2/token" -d grant_type=authorization_code \
  -d client_id=$WEB_CLIENT_ID -d code=$CODE -d redirect_uri=$REDIRECT -d code_verifier=$VERIFIER | jq -r .access_token)

curl -s -H "Authorization: Bearer $TOKEN" <AgentApiUrl>/agent/bestellungen | jq
Enter fullscreen mode Exit fullscreen mode

Expected result: the agent API responds with the two sample orders. The orders Lambda log contains a line with "akteur" (the actor), which according to the docs is the agent's client ID from the act claim. If you send the same customer token directly to the orders API, you get 401 Unauthorized because the audience doesn't match. That's exactly how it should be.

Common Cognito token exchange errors

  • OperationNotEnabledException: The developer guide lists as a prerequisite that token exchange is enabled for your account. Also check the feature plan. Lite doesn't include the feature.
  • Missing auth flow: Without ALLOW_TOKEN_EXCHANGE_DELEGATION, every exchange with an actor token fails. With the impersonation flow alone, only exchanges without an actor token work.
  • Empty or unexpected scopes: If a scope is missing in the customer token or in the agent client's allowed scopes, it drops out of the intersection. The new token then has fewer permissions, and the API answers with 403.
  • Audience without a resource server: The value for audience must be a registered resource server. Typos lead to an error at the token endpoint.
  • Audience and resource together: According to the API reference, you may only specify one of the two, and only one value each.
  • Reset client: If you call UpdateUserPoolClient with only some fields, you delete settings. That's why the script in step 3 reads the configuration first.

Costs and security

Token exchange is only available on the Essentials and Plus plans, which cost more per active user than Lite. On top of that, Cognito bills client credentials tokens by the number of requests, hence the cache for the actor token. Whether the exchange calls themselves cost extra wasn't clear from the announcement. Check the Cognito pricing page before going to production.

On the security side: never log tokens, not even truncated. Keep exchanged tokens short-lived and, if you cache them at all, cache them per customer and only for seconds. Give the agent client as few scopes as possible, because they are your hard upper limit. And treat the agent's client secret like any other secret. How to end sessions on purpose when something goes wrong is covered in the article Cognito session management.

My take

I consider Cognito token exchange one of the most important Cognito features in years, precisely because it is so unspectacular. After all, it solves a problem that suddenly every team has with AI agents: who is acting here, and with which permissions? If you bring agents to production seriously, you need a better answer than “with the user's token”.

I'm critical of two things. First, may_act is missing. With it, the permission for a specific agent to act would be anchored directly in the customer token. Without it, you build that yourself, for example with a trigger and an attribute as shown here. Second, the launch is bumpy: no SDK support, and a CloudFormation schema that doesn't know the flow yet. That will sort itself out in the coming weeks, but until then you need the workarounds from this article.

Even so, I would build new agent projects this way starting today. The act claim alone is worth it. Being able to see in the audit log that an agent, and not the customer, acted is pure gold the first time the business side or your data protection officer asks.

FAQ

What is the difference between token exchange and client credentials?

Client credentials gives you a token for an application without any user context (machine to machine). Token exchange derives a new token from a user's token that still represents that user, just with narrower limits.

Do I need a specific feature plan for Cognito token exchange?

Yes. Your user pool has to be on the Essentials or Plus plan. Lite doesn't support token exchange.

Do I get a refresh token with token exchange?

No. An exchanged token never comes with a refresh token and expires on its own. If the service needs a new one later, it exchanges again with a valid customer token.

Can I exchange tokens from external identity providers?

Yes, if the OIDC or SAML provider is registered in the user pool and the user is already linked there. Cognito always issues Cognito access or ID tokens, never SAML assertions.

Your next step

Pick a service in your landscape that simply passes a user token along today. Register a resource server for the receiving API, switch its authorizer to the new audience and exchange the token in front of it. In short, it's a manageable change with noticeably less risk. And then I'd like to know: how do your agents answer the question of whose behalf they are acting on today? Let me know in the comments.

All code from this article, ready to run: smirowstanitzok/sascha-ms-examples

Sources

This post was created with AI assistance.


👉 Next step: Working with AWS CDK? Grab my printable AWS CDK cheat sheet with commands, concepts and a stack skeleton.

📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).

Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (1)

Collapse
 
joseph437 profile image
Joshua Thompson •

As AI agents become more capable of handling tasks independently, secure authentication is essential to prevent unauthorized access and protect sensitive information. Token exchange offers a useful way to manage permissions while allowing automated systems to perform specific actions. Similar security considerations apply to accessing hennepincounty-mn.org where responsible access and proper handling of information matter. Clear authorization rules help maintain trust and reduce potential risks. It will be interesting to see how these security methods develop as AI adoption grows.