跳到正文
DEV Community· Sascha Mirow-Stanitzok·· 4 天前精選AI 評分78

Cognito token exchange 教學:讓 AI 智能體以受限權限存取 API

Cognito token exchange: let AI agents act safely

AI 導讀

Amazon Cognito token exchange 可把用戶 token 換成僅適用於指定 API、權限更窄且沒有 refresh token 的新 token,讓 AI 智能體代表用戶呼叫後端。

推薦理由

書店訂單範例串連 token exchange、權限收窄與 act claim 審計,並提供 SDK 和 CloudFormation schema 未支援新流程時的部署變通做法。

正文 · 繁體中文

Cognito 權杖交換可讓服務將用戶的權杖換成一個權限較窄的新權杖。自從 AI Agent 開始出現在我接觸的每個專案中,我就一直期待這項功能。每次討論 Agent 架構,遲早都會遇上同一個問題:「Agent 實際上會用哪個權杖呼叫後端 API?」到目前為止,坦白説,答案往往是:直接傳遞用戶的權杖。這樣做行得通,但有點像是把屋匙交給送貨員,好讓他把包裹放在走廊裡。

自 2026 年 11 月 12 日起,Amazon Cognito 可按照 OAuth 標準 RFC 8693 交換權杖。本文會建構一個完整範例:一個書店 AI Agent 使用只能讀取資料、只適用於訂單 API,並會表明 Agent 身分的權杖,讀取客戶的訂單。基礎架構使用 AWS CDK,程式碼則使用 TypeScript。

簡而言之

Cognito 權杖交換會把用戶的權杖換成一個權限較少、只適用於某個指定服務,而且不附帶更新權杖的新權杖。如果加入行為者權杖,新權杖便會包含 act 宣告,讓後端 API 知道是 Agent 代表用戶執行操作。不過,目前有個限制:AWS SDK 和 CloudFormation 架構都尚未支援這項新功能。幸好,可以透過權杖端點和一個小型指令碼繞過這兩個限制。

本文會介紹

  • 甚麼是權杖交換,以及何時適合使用模擬身分或委派
  • 如何為 AI Agent 提供一個範圍嚴格受限、只適用於某個 API 的權杖
  • 後端 API 如何利用 act 宣告識別 Agent
  • 如何使用 AWS CDK、TypeScript 和 Vitest 建構整套系統
  • 推出時會遇到哪些陷阱

甚麼是 Cognito 權杖交換?

權杖交換是 OAuth 2.0 的一項延伸功能。服務會提交現有權杖,並換取一個新權杖。提交的權杖稱為主體權杖,代表服務所代為行事的人士。你也可以選擇加入行為者權杖,用來識別實際執行操作的服務,例如 Agent 或 MCP 伺服器。

先介紹幾個術語,方便初學者理解。存取權杖是經簽署的 JSON Web Token (JWT),API 每次收到呼叫時都會檢查這個權杖。範圍説明權杖可以執行哪些操作,例如 bestellungen/lesen(德文,意為「訂單/讀取」)。受眾(aud 宣告)指出權杖是發給哪個接收方。在 Cognito 中,受眾對應一個資源伺服器,也就是你在用戶集區中註冊的 API,並可為它定義自訂範圍。

Cognito 權杖交換將這些組件連繫起來:新權杖只有一個受眾,所含範圍不會超出原有權杖,而且不會附帶更新權杖。你可透過權杖端點 /oauth2/token 或新的 API 操作 GetDerivedToken 啟動交換。你需要使用 Essentials 或 Plus 方案的用戶集區;Lite 方案不包括這項功能。

為甚麼直接傳遞用戶權杖會有問題

想像一下網上書店的聊天助理。客戶問:「我的訂單到哪裏了?」Agent 需要從訂單 API 取得資料才能回答。最方便的做法是:直接轉發客戶用來呼叫聊天功能的存取權杖。

不過,這會同時帶來幾個問題。首先,權杖的權限過大,因為它可能也獲準取消訂單,但 Agent 應該只能讀取資料。此外,這個權杖原本並非為訂單 API 簽發,而是為聊天應用程式簽發。最後,訂單 API 無法分辨是客戶本人點擊操作,還是語言模型自行決定採取行動。對於審計日誌、責任歸屬問題,以及一般除錯工作來説,這都是一個盲點。

目前的替代做法是自行簽發權杖:自行管理金鑰、金鑰輪替,以及組合權杖聲明的程式碼。這樣做可行,但這類安全性程式碼正是我寧願不要自行維護的東西。使用 Cognito 權杖交換後,這項工作便由用戶集區接手,而後端 API 會像驗證其他 Cognito 權杖一樣驗證新權杖。

權杖交換中的身份冒充或委派

Cognito 提供兩種變體。你會得到哪一種,完全取決於你在交換時有否傳送行為者權杖。

變體 行為者權杖 新權杖包含的內容 適用情況
身份冒充 否 權杖看起來像是用戶直接採取行動,不含 act 聲明 只需要權限較受限的權杖的自家後端服務
委派 是 另外包含 act 聲明,列明中介者的身份 AI Agent、MCP 伺服器,以及任何需要在審計日誌中獨立記錄的對象

對於 AI Agent,我幾乎總是選擇委派。額外的工作只是多處理一個權杖。作為回報,API 始終知道實際採取行動的是誰。舉例來説,當商店的後端呼叫內部 API,而兩者之間的區別並不重要時,身份冒充便很方便。

你可透過每個應用程式用戶端的驗證流程 ALLOW_TOKEN_EXCHANGE_IMPERSONATION 和 ALLOW_TOKEN_EXCHANGE_DELEGATION 啟用這些變體。當然,同一用戶端亦可同時啟用兩者。

Cognito 在交換期間提供的保障

安全方面的保障才是我喜歡這項功能的真正原因。根據開發人員指南:

  • 只可收窄,不可擴大:新權杖中的範圍,是所要求的範圍、主體權杖的範圍,以及進行交換的應用程式用戶端獲準授予的所有範圍三者的交集。
  • 不會有重新整理權杖:交換所得的權杖會自行到期。客戶的工作階段一旦結束,便沒有人可以再以該權杖簽發新權杖。
  • 會檢查原始權杖:Cognito 會驗證主體權杖的簽署、到期時間及撤銷狀態,例如在全域登出後。已停用或未確認的用戶不會獲發權杖。
  • 單一受眾:新權杖只對一個已註冊的資源伺服器有效。

有兩個限制需要注意。Cognito 不會評估 RFC 8693 中的 may_act 聲明。因此,你無法預先在原始權杖中聲明哪些 Agent 可以採取行動。你必須自行實作這項規則,例如透過 Agent 用戶端的範圍或 Lambda 觸發程序。此外,權杖交換不會建立用戶:如果主體權杖來自外部身份提供者,該用戶必須已連結至用戶集區。

範例:書店 Agent 讀取訂單

我們虛構的書店由三個部分組成。網頁應用程式透過 Cognito 讓客戶登入,並使用該權杖呼叫 Agent API。接着,Agent Lambda 會交換該權杖,並代表她呼叫訂單 API。最後,訂單 API 只接受受眾為 bestellungen 的權杖,並在日誌中記錄是否有 Agent 參與。

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

範例中的委派:只有受眾為 “bestellungen” 的交換所得權杖,才能通過訂單 API。

還有一個細節令整個模式完整:Cognito 一般登入流程發出的存取權杖不含 aud 聲明,只有網頁應用程式的 client_id。API Gateway JWT 授權器會將已設定的受眾與 aud 比較;如果缺少該值,則會與 client_id 比較。如果你將訂單 API 的受眾設定為 bestellungen,它便會拒絕客戶原有的權杖。只有經過交換流程的權杖才能通過。

先決條件

  • AWS 帳戶,以及具備有效憑證的 AWS CLI
  • Node.js 22 或更新版本(我以 Node.js 24 測試)
  • AWS CDK v2,以及已執行 bootstrap 的帳戶(npx cdk bootstrap)
  • curl、jq 和 openssl,供最後的測試使用
  • 具備 OAuth 2.0 和 JWT 的基本知識會有幫助,但並非必須

逐步教學:使用 AWS CDK 進行 Cognito 權杖交換

步驟 1:建立專案

建立一個空目錄並安裝套件。此專案使用 ES 模組和 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

tsconfig.json、cdk.json 和 bin/app.ts 這些檔案都是標準檔案。你可以在文末連結的範例程式碼庫找到它們。

步驟 2:用戶集區、資源伺服器和應用程式用戶端

此堆疊會建立一個採用 Essentials 方案的用戶集區、兩個資源伺服器和兩個應用程式用戶端。網頁用戶端是公開用戶端,並使用帶有 PKCE 的授權碼流程。此外,代理程式用戶端會取得一個密碼和用戶端憑證流程,讓它可以使用自己的權杖識別身分。因此,其範圍 bestellungen/lesen 是一個上限:無論客戶獲準進行甚麼操作,代理程式透過交換流程都無法取得超出此範圍的權限。

// 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 });
  }
}

理論上,代理程式用戶端可以透過用戶端憑證流程自行取得帶有 bestellungen/lesen 的權杖。不過,該權杖不會有 aud 聲明,而 client_id 則會是代理程式的 ID。因此,訂單 API 會拒絕該權杖。沒有交換流程,也就是沒有客戶參與,代理程式便無法存取訂單。

步驟 3:部署後啟用權杖交換流程

第一個陷阱就在這裏。理想情況下,我會直接在堆疊中設定 ALLOW_TOKEN_EXCHANGE_DELEGATION。不過,使用 aws-cdk-lib 2.276.0 時,cdk synth 會因此發出警告 W3030:隨附的 CloudFormation 結構描述只認得舊有值。因此,我從堆疊中移除該值,並在部署後用指令碼設定。

第二個陷阱也在等着你。UpdateUserPoolClient 會將所有未提供的欄位重設為預設值。如果你只傳入驗證流程,範圍和 OAuth 設定就會遺失。因此,輔助函式會先讀取目前的設定,再只加入新流程:

// 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(', '));

請留意:之後任何會修改代理程式用戶端的 cdk deploy,都可能再次移除該流程。在 CloudFormation 認得該值之前,每次部署後都要在你的 pipeline 中執行該指令碼。之後便可將它重新加入堆疊。

步驟 4:呼叫權杖端點

第二個陷阱:@aws-sdk/client-cognito-identity-provider 3.1168.0,即 11 月 12 日的最新版本,尚未提供 GetDerivedTokenCommand。botocore 1.44.2 也不認得這個操作。這不成問題,因為權杖端點使用標準 OAuth。只需幾行 fetch 便足夠:

// 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'));
}

參數名稱與 RFC 8693 完全相同:subject_token 用於客戶權杖,actor_token 用於代理程式權杖,而 audience 用於資源伺服器。權杖端點需要用戶集區設定網域;堆疊已在步驟 2 建立網域。

步驟 5:代理程式交換權杖

在冷啟動時,代理程式 Lambda 會透過 DescribeUserPoolClient 取得用戶端密碼,而非將密碼儲存在環境變數中。它亦會快取透過用戶端憑證取得的 actor 權杖,直至權杖即將到期。這樣可減少呼叫次數,而 Cognito 會對 M2M 權杖另行收費。

// 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 }) };
};

在實際的 Agent 中,這段程式碼會放在語言模型呼叫的工具內,例如 MCP 伺服器的工具處理程序中。我在文章 MCP server on Lambda 中示範如何在 Lambda 上執行 MCP 伺服器。

🎬 使用委派功能進行權杖交換的流程 – 這個動畫示意圖只會在我的網站上播放:前往 sascha-ms.de 觀看

第 6 步:訂單 API 評估 act claim

API Gateway 會檢查簽章、到期時間、受眾和權限範圍。其後,背後的 Lambda 會決定 Agent 可以執行哪些操作。為了方便測試,這項規則會放在獨立函式中:

// 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 };
}
// 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) };
};

請注意,Lambda 讀取 payload 時不會自行驗證簽章。這裡這樣做沒有問題,因為必須先通過 JWT 授權器,才能存取該路由。如果其他來源也會呼叫 Lambda,便要自行驗證簽章,例如使用 aws-jwt-verify 程式庫。

此外,取消路由展示了兩種做法的分別。如果客戶想自行取消,商店的後端可以透過冒充方式取得帶有 bestellungen/stornieren 的權杖,因此不會有 act claim。另一方面,Agent 永遠不會取得該權限範圍。即使意外取得,政策也會封鎖所有帶有 act claim 的呼叫。

第 7 步:透過 pre token generation trigger 選擇加入

用戶應自行決定是否允許 Agent 代其行事。進行交換時,Cognito 會以來源 TokenGeneration_TokenExchange 呼叫 pre token generation trigger。如果函式擲出錯誤,交換便會失敗。我利用這個機制,透過屬性 custom:ki_freigabe(德文意指「AI 同意」)讓用戶選擇加入:

// 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;
};

Trigger 會收到用戶的屬性,但不會收到原始權杖。它無法在交換期間新增權限範圍,只能修改 claim、隱藏權限範圍或拒絕要求。

第 8 步:測試、部署及試用

政策和權杖輔助函式都是純函式,無須使用 AWS 也可以測試。以下是 Vitest 測試的一段摘錄:

// 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/);
  });
});
npx tsc --noEmit
npx vitest run
npx cdk deploy

部署完成後,啟用此流程並建立測試客戶。堆疊輸出中會列出相關 ID。

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

如要取得含自訂權限範圍的權杖,必須透過 OAuth 登入。使用 PKCE 時,即使沒有前端也能完成:在瀏覽器開啟輸出的 URL 並登入。瀏覽器無法載入 localhost 重新導向頁面,但網址列仍會顯示 code 參數。

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

預期結果:Agent API 會回傳兩筆範例訂單。訂單 Lambda 的日誌會有一行包含 "akteur"(行動者)的記錄;根據文件,這是 act claim 中 Agent 的用戶端 ID。如果直接把同一個客戶權杖傳給訂單 API,便會收到 401 Unauthorized,因為受眾不符。這正是預期結果。

Cognito 權杖交換常見錯誤

  • OperationNotEnabledException:開發人員指南列明,權杖交換必須先在你的帳戶中啟用。亦請檢查功能方案;Lite 不包括這項功能。
  • 缺少驗證流程:若沒有 ALLOW_TOKEN_EXCHANGE_DELEGATION,所有使用行動者權杖的交換都會失敗。若只使用冒充流程,則只有不帶行動者權杖的交換才會成功。
  • 權限範圍為空或不符合預期:如果客戶權杖或 Agent 用戶端的允許權限範圍中缺少某個權限範圍,該權限範圍便會從交集結果中剔除。新權杖的權限會因此減少,而 API 會回應 403。
  • 受眾未對應資源伺服器:audience 的值必須是已註冊的資源伺服器。拼寫錯誤會令權杖端點回報錯誤。
  • 受眾和資源同時指定:根據 API 參考資料,兩者只能指定其中一項,而且每項只能指定一個值。
  • 重設用戶端:如果呼叫 UpdateUserPoolClient 時只提供部分欄位,就會刪除設定。因此,第 3 步的指令碼會先讀取設定。

成本與安全性

權杖交換只適用於 Essentials 和 Plus 方案,這兩種方案每名活躍用戶的費用都高於 Lite。此外,Cognito 按請求次數對 client credentials 權杖收費,因此需要快取 actor 權杖。公告並未清楚説明權杖交換呼叫本身是否會額外收費。正式推出前,請查閲 Cognito 的定價頁面。

在安全方面:切勿記錄權杖,即使只記錄截短版本也不行。交換所得的權杖應有較短的有效期;如果要快取,就應按客戶分開快取,而且只快取數秒。為 Agent 用戶端設定的權限範圍應盡可能少,因為這些範圍就是硬性上限。並且要像保管其他密碼一樣妥善保管 Agent 的用戶端密鑰。遇上問題時如何主動結束工作階段,請參閲文章Cognito 工作階段管理。

我的看法

我認為 Cognito 權杖交換是 Cognito 多年來最重要的功能之一,正正因為它看起來平平無奇。畢竟,它解決了每個團隊突然都要面對的 AI Agent 問題:現在是誰在執行操作?使用哪些權限?如果你認真打算讓 Agent 正式投入使用,就需要比「使用用戶的權杖」更好的答案。

我對兩件事有所保留。首先,缺少 may_act。有了它,特定 Agent 的行動權限就能直接錨定在客戶權杖中。缺少這項功能時,你就要自行建構,例如像本文所示,使用觸發程序和屬性。其次,這次推出過程不太順利:沒有 SDK 支援,而且 CloudFormation 結構描述尚未支援這個流程。未來幾星期應會逐步解決,但在此之前,你需要使用本文介紹的替代方案。

即使如此,從今天起,我仍會用這種方式建構新的 Agent 專案。光是 act 聲明就值得採用。第一次遇到業務部門或資料保護主任查詢時,能在稽核記錄中看到執行操作的是 Agent,而不是客戶,這點極具價值。

常見問題

權杖交換和 client credentials 有甚麼分別?

Client credentials 會在沒有任何用戶背景的情況下,為應用程式提供權杖(機器對機器)。權杖交換則會根據用戶的權杖產生新權杖;新權杖仍代表該用戶,只是限制範圍較窄。

使用 Cognito 權杖交換需要特定功能方案嗎?

需要。你的用戶集區必須採用 Essentials 或 Plus 方案。Lite 不支援權杖交換。

使用權杖交換會取得重新整理權杖嗎?

不會。交換所得的權杖不會附帶重新整理權杖,並會自行到期。如果服務之後需要新權杖,就要使用有效的客戶權杖再次進行交換。

我可以交換外部身份提供者的權杖嗎?

可以,但 OIDC 或 SAML 提供者必須已在用戶集區註冊,而且用戶已在該處連結。Cognito 一律會發出 Cognito 存取權杖或 ID 權杖,不會發出 SAML assertion。

下一步

在你的系統環境中,挑選一項目前只會轉送用戶令牌的服務。為接收端 API 註冊資源伺服器,將其授權器切換至新的受眾,並在該服務前方交換令牌。總括而言,這項變更容易管理,風險亦明顯較低。接着我想知道:你的 Agent 目前如何回答自己是代表誰行事?歡迎在留言區告訴我。

本文的所有程式碼,已可直接執行:smirowstanitzok/sascha-ms-examples

來源

本文由 AI 協助撰寫。


👉 下一步:使用 AWS CDK?取得我的可列印版 AWS CDK 速查表,內含命令、概念及堆疊骨架。

📬 掌握最新資訊:透過 RSS、瀏覽器推送通知或每週電子報(德文版),閲讀無伺服器技術、AI 及帶領科技團隊方面的新文章。

最初刊載於 sascha-ms.de。更多關於無伺服器技術、日常開發中的 AI 及帶領科技團隊的文章:sascha-ms.de/en

來源:DEV Community · dev.to