Cognitoのトークン交換をAgentCore Gatewayで試してみた

Cognitoのトークン交換をAgentCore Gatewayで試してみた

Amazon CognitoがOAuth 2.0のトークン交換に対応したので、AgentCore Gatewayと組み合わせて試してみました!
2026.11.25

はじめに

こんにちは、Amazon Bedrock AgentCoreが大好きなコンサル部の神野です。

Amazon CognitoがOAuth 2.0のトークン交換(RFC 8693)に対応しました!

https://aws.amazon.com/jp/about-aws/whats-new/2026/11/cognito-token-exchange/

AgentCore Gatewayと組み合わせて、エージェントがユーザーの代わりにAPIを呼び出す流れをサクッと試してみます。

Entra IDで試したOn-Behalf-Of(OBO)のCognitoバージョンと考えるとわかりやすいかと思います!

https://dev.classmethod.jp/articles/agentcore-identity-obo-entra-id/

Cognito側でスコープを絞る使い方は、suzuki.ryoさんの記事も参考になるので、こちらも合わせてご参照ください!

https://dev.classmethod.jp/articles/cognito-oauth2-token-exchange-scoped-token/

主な変更点

まず簡単にトークン交換の仕組みをおさえていきましょう!

トークン交換は手元のトークンを別の宛先向けの新しいトークンに取り替えるOAuth 2.0の仕組みです。ユーザーの代わりに別のサービスを呼び出すこと(On-Behalf-Of、略してOBO)に使えます。

たとえば社内アシスタントAIが社員の代わりに購買システムを呼び出す場面を想定してみます。

社員が社内アシスタントに備品の注文状況の確認を頼み、アシスタントが社員の代わりに購買システムを呼び出したい場面。購買システムは誰の依頼でどこまで許可してよいのかを知りたい

この場面で社員のトークンをそのまま渡すと購買システム以外の色々なシステムも呼び出せてしまい、あまりよろしくありません。AIエージェントに勝手に変なアクションをされたら怖いですよね。

社員のトークンには宛先が入っておらず、スコープ(権限の範囲)も広いままだからです。

そのまま渡したトークンは購買システム以外も呼び出せてしまうが、交換したトークンは宛先が購買システムだけで権限も読み取りに絞られている

OAuth 2.0のセキュリティベストプラクティス(RFC 9700)でも、アクセストークンの権限は用途に必要な最小限にして宛先を特定のサーバーに限定するよう勧めています。

https://www.rfc-editor.org/rfc/rfc9700#section-2.3

そこでアシスタントは社員のトークンと自分のトークンをCognitoに渡して、購買システム宛てで権限を絞ったトークンを受け取ります。これでAIエージェントに外部システムを安全に使わせられます!

アシスタントが社員のトークンと自分のトークンをCognitoに渡して購買システム宛てのトークンに交換し、購買システムを呼び出す

購買システムは交換されたトークンを受け取って次のことを判断できます。

購買システムは交換したトークンのaud・username・act・scopeから、自分宛てか、誰の依頼か、誰が代理で動いているか、何を許可するかを判断できる

誰の依頼かも代理かどうかも、しっかりわかりますね!!

その他

交換はトークンエンドポイント(トークンを発行するURL /oauth2/token)か新しい GetDerivedToken API で実行できます。
Essentials・Plusの機能プランが対象で、リフレッシュトークンは発行されません。

https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-token-exchange.html

今回の構成とトークンの流れ

簡単に理屈がわかったところで試してみましょうか!

今回は注文API(購買システムの代わり)をAPI Gateway(HTTP API)とLambdaで作り、宛先が orders-api のトークンだけを受け付けるようにしました。Lambdaは届いたトークンのユーザー名・宛先・スコープ・代理の情報を返します。

トークンは次の順にやりとりしていきます。

ユーザーがサインインしてトークンを受け取り、Gatewayのツールを呼び出す。GatewayはAgentCore Identity経由でユーザーのトークンとアクタートークンをCognitoに渡して注文API宛てのトークンに交換し、そのトークンで注文APIを呼び出す

  1. ユーザーがCognitoでサインインしてトークンを受け取る(宛先は入っていない)
  2. そのトークンでGatewayのツールを呼び出す
  3. GatewayがAgentCore Identityを通して、ユーザーのトークンとエージェント自身のトークン(アクタートークン)をCognitoに渡す
  4. Cognitoが注文API宛てのトークンを返す
  5. Gatewayがそのトークンで注文APIを呼び出す
  6. 注文APIがトークンの宛先・ユーザー・代理・スコープを見て判断する

「やってみる」では、手順3・4をAWS CLIで試してからGatewayに任せます。

リージョンはバージニア北部(us-east-1)、AWS CLIは2.42.3です(交換に使う get-derived-token は2.40.4以降)。記事中のユーザー名は demo-user に置き換えています。

作業フォルダとJWTを表示する decode.py
作業フォルダのセットアップ
mkdir cognito-token-exchange && cd cognito-token-exchange
uv init --no-readme
uv add httpx
decode.py
import sys, base64, json
keys = sys.argv[1:]
p = sys.stdin.read().strip().split(".")[1]
p += "=" * (-len(p) % 4)
c = json.loads(base64.urlsafe_b64decode(p))
print(json.dumps({k: c.get(k) for k in keys} if keys else c, ensure_ascii=False, indent=1))

やってみる

ではさっそくやってみましょう!

Cognitoと注文APIを準備する

まずCognitoには次のリソースサーバーとアプリクライアントを作ります。

ユーザープールにはリソースサーバーagentとorders-api、アプリクライアントfrontendとagentを作る。agentにはトークン交換の認証フローを入れる

今回の新しい設定は、agent クライアントでトークン交換を許可する認証フローです。

認証フローは2つ入れました!
ALLOW_TOKEN_EXCHANGE_DELEGATION はエージェント自身のトークンも付ける交換で、発行されるトークンに代理の情報(act)が入ります。

ALLOW_TOKEN_EXCHANGE_IMPERSONATION はエージェントのトークンを付けない交換で、本人が呼び出したのと見分けがつきません。今回はどちらも試します。

agentクライアントの作成(抜粋)
aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name agent --generate-secret \
  --allowed-o-auth-flows-user-pool-client --allowed-o-auth-flows client_credentials \
  --allowed-o-auth-scopes agent/invoke orders-api/read \
  --explicit-auth-flows ALLOW_TOKEN_EXCHANGE_DELEGATION ALLOW_TOKEN_EXCHANGE_IMPERSONATION

ドメインはマネージドログインのバージョン2で作ります。

Cognitoと注文APIを作るスクリプト
setup_cognito.sh
set -euo pipefail
export AWS_REGION=us-east-1
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

# Essentials プランのユーザープール
POOL_ID=$(aws cognito-idp create-user-pool --pool-name obo-demo \
  --user-pool-tier ESSENTIALS --query UserPool.Id --output text)

# トークンエンドポイントを使うためのドメイン
DOMAIN=obo-demo-${ACCOUNT_ID}
aws cognito-idp create-user-pool-domain --user-pool-id "$POOL_ID" \
  --domain "$DOMAIN" --managed-login-version 2 > /dev/null

# リソースサーバー(エージェントと注文API)
aws cognito-idp create-resource-server --user-pool-id "$POOL_ID" \
  --identifier agent --name agent \
  --scopes ScopeName=invoke,ScopeDescription=invoke > /dev/null
aws cognito-idp create-resource-server --user-pool-id "$POOL_ID" \
  --identifier orders-api --name orders-api \
  --scopes ScopeName=read,ScopeDescription=read ScopeName=write,ScopeDescription=write > /dev/null

# ユーザーがサインインする画面側のクライアント
FRONT_CLIENT_ID=$(aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name frontend --no-generate-secret \
  --allowed-o-auth-flows-user-pool-client --allowed-o-auth-flows code \
  --allowed-o-auth-scopes openid agent/invoke orders-api/read orders-api/write \
  --callback-urls http://localhost:8765/callback \
  --supported-identity-providers COGNITO \
  --explicit-auth-flows ALLOW_REFRESH_TOKEN_AUTH \
  --query UserPoolClient.ClientId --output text)

# サインイン画面のブランディング(Cognitoのデフォルトのデザイン)
aws cognito-idp create-managed-login-branding --user-pool-id "$POOL_ID" \
  --client-id "$FRONT_CLIENT_ID" --use-cognito-provided-values > /dev/null

# トークンを交換するエージェント側のクライアント
AGENT_CLIENT_ID=$(aws cognito-idp create-user-pool-client --user-pool-id "$POOL_ID" \
  --client-name agent --generate-secret \
  --allowed-o-auth-flows-user-pool-client --allowed-o-auth-flows client_credentials \
  --allowed-o-auth-scopes agent/invoke orders-api/read \
  --explicit-auth-flows ALLOW_TOKEN_EXCHANGE_DELEGATION ALLOW_TOKEN_EXCHANGE_IMPERSONATION \
  --query UserPoolClient.ClientId --output text)

cat > .env.ids <<EOV
AWS_REGION=us-east-1
POOL_ID=$POOL_ID
DOMAIN=$DOMAIN
FRONT_CLIENT_ID=$FRONT_CLIENT_ID
AGENT_CLIENT_ID=$AGENT_CLIENT_ID
EOV
cat .env.ids
orders_api/app.py
import base64
import json

def handler(event, context):
    # API Gatewayで検証済みのトークンから、呼び出し元の情報を取り出す
    token = event["headers"]["authorization"].split()[1]
    payload = token.split(".")[1]
    claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
    caller = {k: claims.get(k) for k in ("username", "aud", "scope", "act")}

    if event["routeKey"].startswith("POST"):
        return {"statusCode": 201, "body": json.dumps({"created": True, "caller": caller})}
    orders = [{"id": "A-1001", "item": "ノートPC", "status": "発送済み"},
              {"id": "A-1002", "item": "モニター", "status": "準備中"}]
    return {"statusCode": 200, "body": json.dumps({"orders": orders, "caller": caller}, ensure_ascii=False)}
setup_orders_api.sh
set -euo pipefail
source .env.ids
export AWS_REGION
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

# Lambda
aws iam create-role --role-name obo-orders-api-role --assume-role-policy-document '{
  "Version":"2012-10-17","Statement":[{"Effect":"Allow",
  "Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}' > /dev/null
aws iam attach-role-policy --role-name obo-orders-api-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
sleep 10
(cd orders_api && zip -q ../orders_api.zip app.py)
FUNC_ARN=$(aws lambda create-function --function-name obo-orders-api \
  --runtime python3.14 --handler app.handler --zip-file fileb://orders_api.zip \
  --role arn:aws:iam::${ACCOUNT_ID}:role/obo-orders-api-role \
  --query FunctionArn --output text)

# HTTP API と JWT オーソライザー(宛先が orders-api のトークンだけ受け付ける)
API_ID=$(aws apigatewayv2 create-api --name obo-orders-api --protocol-type HTTP \
  --query ApiId --output text)
AUTH_ID=$(aws apigatewayv2 create-authorizer --api-id "$API_ID" --name cognito \
  --authorizer-type JWT --identity-source '$request.header.Authorization' \
  --jwt-configuration "Issuer=https://cognito-idp.${AWS_REGION}.amazonaws.com/${POOL_ID},Audience=orders-api" \
  --query AuthorizerId --output text)
INTEG_ID=$(aws apigatewayv2 create-integration --api-id "$API_ID" \
  --integration-type AWS_PROXY --integration-uri "$FUNC_ARN" \
  --payload-format-version 2.0 --query IntegrationId --output text)

# 読み取りは orders-api/read、作成は orders-api/write が必要
aws apigatewayv2 create-route --api-id "$API_ID" --route-key 'GET /orders' \
  --target "integrations/$INTEG_ID" --authorization-type JWT \
  --authorizer-id "$AUTH_ID" --authorization-scopes orders-api/read > /dev/null
aws apigatewayv2 create-route --api-id "$API_ID" --route-key 'POST /orders' \
  --target "integrations/$INTEG_ID" --authorization-type JWT \
  --authorizer-id "$AUTH_ID" --authorization-scopes orders-api/write > /dev/null
aws apigatewayv2 create-stage --api-id "$API_ID" --stage-name '$default' --auto-deploy > /dev/null

aws lambda add-permission --function-name obo-orders-api --statement-id apigw \
  --action lambda:InvokeFunction --principal apigateway.amazonaws.com \
  --source-arn "arn:aws:execute-api:${AWS_REGION}:${ACCOUNT_ID}:${API_ID}/*" > /dev/null

echo "API_ID=$API_ID" >> .env.ids
echo "ORDERS_API_URL=https://${API_ID}.execute-api.${AWS_REGION}.amazonaws.com" >> .env.ids
tail -2 .env.ids
Cognitoと注文APIを作成してユーザーを追加
bash setup_cognito.sh
mkdir orders_api   # ここに app.py を保存する
bash setup_orders_api.sh
set -a && source .env.ids && set +a

aws cognito-idp admin-create-user --user-pool-id "$POOL_ID" \
  --username demo-user --message-action SUPPRESS
aws cognito-idp admin-set-user-password --user-pool-id "$POOL_ID" \
  --username demo-user --password '<任意のパスワード>' --permanent

ユーザーのトークンをそのまま渡してみる

試しに手順3・4を飛ばして、ユーザーのトークンを注文APIにそのまま渡してみます。

login.py とサインイン
login.py
"""Cognitoのマネージドログインでサインインし、ユーザーのアクセストークンを user_token.txt に保存する"""
import base64
import hashlib
import http.server
import os
import secrets
import urllib.parse
import webbrowser

import httpx

DOMAIN = os.environ["DOMAIN"]
CLIENT_ID = os.environ["FRONT_CLIENT_ID"]
REGION = os.environ.get("AWS_REGION", "us-east-1")
BASE = f"https://{DOMAIN}.auth.{REGION}.amazoncognito.com"
REDIRECT_URI = "http://localhost:8765/callback"
SCOPES = "openid agent/invoke orders-api/read orders-api/write"

verifier = secrets.token_urlsafe(64)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(16)
code: str | None = None

class Callback(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        global code
        q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
        ok = q.get("state", [None])[0] == state
        if ok:
            code = q.get("code", [None])[0]
        self.send_response(200 if ok else 400)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.end_headers()
        msg = "サインインできました。ターミナルに戻ってください。" if ok else "stateが一致しません。"
        self.wfile.write(msg.encode())

    def log_message(self, *args):
        pass

url = f"{BASE}/oauth2/authorize?" + urllib.parse.urlencode({
    "response_type": "code",
    "client_id": CLIENT_ID,
    "redirect_uri": REDIRECT_URI,
    "scope": SCOPES,
    "state": state,
    "code_challenge": challenge,
    "code_challenge_method": "S256",
})
print(url)
webbrowser.open(url)

server = http.server.HTTPServer(("localhost", 8765), Callback)
while code is None:
    server.handle_request()

res = httpx.post(f"{BASE}/oauth2/token", data={
    "grant_type": "authorization_code",
    "client_id": CLIENT_ID,
    "code": code,
    "redirect_uri": REDIRECT_URI,
    "code_verifier": verifier,
})
res.raise_for_status()
with open("user_token.txt", "w") as f:
    f.write(res.json()["access_token"])
print("user_token.txt に保存しました")
サインインしてトークンを確認する
uv run login.py
USER_TOKEN=$(cat user_token.txt)
uv run decode.py client_id aud scope username < user_token.txt
実行結果
{
 "client_id": "<frontendクライアントのID>",
 "aud": null,
 "scope": "openid agent/invoke orders-api/write orders-api/read",
 "username": "demo-user"
}

このまま注文APIに渡すと、宛先(aud)が入っていないので予想通り検証で401になりました!

そのまま注文APIへ送る
curl -s -w "\nHTTP %{http_code}\n" "$ORDERS_API_URL/orders" -H "Authorization: Bearer $USER_TOKEN"
実行結果
{"message":"Unauthorized"}
HTTP 401

ではトークンを交換して試してみましょうか。

AWS CLIで交換する

今度は手順3・4のトークン交換をAWS CLIで試します!

agent クライアントとして、ユーザーのトークンと agent 自身のトークンを渡して交換します。agent 自身のトークンは get-client-token でも取れますが、トークン交換の認証フローを入れたクライアントでは使えませんでした・・・
そこでトークンエンドポイントから取っています。

アクター付きで交換する
AGENT_CLIENT_SECRET=$(aws cognito-idp describe-user-pool-client --user-pool-id "$POOL_ID" \
  --client-id "$AGENT_CLIENT_ID" --query UserPoolClient.ClientSecret --output text)
TOKEN_URL="https://${DOMAIN}.auth.${AWS_REGION}.amazoncognito.com/oauth2/token"

ACTOR_TOKEN=$(curl -s -u "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" "$TOKEN_URL" \
  -d grant_type=client_credentials -d scope=agent/invoke | jq -r .access_token)

EXCHANGED_TOKEN=$(aws cognito-idp get-derived-token --client-id "$AGENT_CLIENT_ID" \
  --client-secret "$AGENT_CLIENT_SECRET" \
  --subject-token "$USER_TOKEN" --subject-token-type ACCESS_TOKEN \
  --actor-token "$ACTOR_TOKEN" --actor-token-type ACCESS_TOKEN \
  --audiences orders-api --scopes orders-api/read \
  --query IssuedToken --output text)

echo "$EXCHANGED_TOKEN" | uv run decode.py client_id aud scope username act
実行結果
{
 "client_id": "<agentクライアントのID>",
 "aud": "orders-api",
 "scope": "orders-api/read",
 "username": "demo-user",
 "act": {
  "sub": "<agentクライアントのID>",
  "client_id": "<agentクライアントのID>",
  "iss": "https://cognito-idp.us-east-1.amazonaws.com/<ユーザープールID>",
  "token_type": "urn:ietf:params:oauth:token-type:access_token"
 }
}

宛先が注文APIになり、スコープは読み取りだけに絞られました。代理で呼び出す側として agent クライアントも入っていますね!

このトークンで呼び出すと一覧の取得(GET)は200になり、書き込みのスコープが必要な作成(POST)は403でした。そのまま渡したときと並べると次のとおりです。

ユーザーのトークンはaudがなく401。交換したトークンはaudがorders-apiでactにagentが入り、GETは200でPOSTは403

実行結果(GET /orders)
実行結果(GET /orders)
{"orders": [{"id": "A-1001", "item": "ノートPC", "status": "発送済み"}, ...], "caller": {"username": "demo-user", "aud": "orders-api", "scope": "orders-api/read", "act": {"sub": "<agentクライアントのID>", ...}}}
HTTP 200

ほかにも次のことを確認しました。

  • agent 自身のトークンを渡さずに交換すると、act(誰が代わりに呼び出したか)が入らず、注文APIからは本人が直接呼び出したのと見分けがつかないトークンになる
  • agent クライアントに許可していない書き込みのスコープを求めると、交換が拒否される

許可していないスコープを求めると、やはり拒否されますね。

余談みたいな話ですが、act のないトークンでも注文APIは今回の作りだと通ります。

act なしのトークンで注文APIを呼び出した結果(抜粋)
{"orders": [...], "caller": {"username": "demo-user", "aud": "orders-api", "scope": "orders-api/read", "act": null}}
HTTP 200

今回使っているAPI Gateway のJWTオーソライザーが見るのは発行元・宛先・有効期限・スコープなどで、act は見ないためです。代理の呼び出しだけを受け付けたいなら、actもチェックするような作りにしないといけないですね!

https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html

AgentCore Gatewayに任せる

手動で試した手順3〜5を、AgentCore Gatewayに任せてみましょう!

AgentCore IdentityにはCognitoでトークンを交換するための接続設定(OAuthプロバイダー)を作ります。ここでエージェント自身のトークンを付けるように指定すると、自動で取得して一緒に渡してくれます。

プロバイダーの設定(抜粋)
"customOauth2ProviderConfig": {
  "oauthDiscovery": {"discoveryUrl": "https://cognito-idp.us-east-1.amazonaws.com/<ユーザープールID>/.well-known/openid-configuration"},
  "clientId": "<agentクライアントのID>",
  "clientSecret": "<agentクライアントのシークレット>",
  "clientAuthenticationMethod": "CLIENT_SECRET_BASIC",
  "onBehalfOfTokenExchangeConfig": {
    "grantType": "TOKEN_EXCHANGE",
    "tokenExchangeGrantTypeConfig": {"actorTokenContent": "M2M", "actorTokenScopes": ["agent/invoke"]}
  }
}

Gatewayには注文APIをツールとして登録し、注文APIを呼び出すときの認証(アウトバウンド認証)にこのプロバイダーとトークン交換を指定します。

ターゲットのアウトバウンド認証(抜粋)
"oauthCredentialProvider": {
  "providerArn": "<プロバイダーのARN>",
  "scopes": ["orders-api/read"],
  "customParameters": {
    "audience": "orders-api",
    "subject_token_type": "urn:ietf:params:oauth:token-type:access_token"
  },
  "grantType": "TOKEN_EXCHANGE"
}

Cognitoに送られる値は次のとおりです。宛先とトークンの種類を追加のパラメーターで指定するのがポイントでした。

AgentCore IdentityがCognitoに送るトークン交換の値。audienceとsubject_token_typeはターゲットのcustomParametersで指定する

宛先(audience)を省くと宛先のないトークンが返り、注文APIで拒否されます。

また、AgentCore Identityはトークンの種類(subject_token_type)をデフォルトで jwt として送りますが、Cognitoは受け付けないので access_token に上書きしています。jwt のまま送ったときの応答は下記のようにエラーで返ってきました。

subject_token_typeにjwtを指定したときのCognitoの応答
{"error":"invalid_request","error_description":"Unsupported token type: urn:ietf:params:oauth:token-type:jwt"}
Gatewayを作るスクリプト

OpenAPIの定義にある <注文APIのURL> は、.env.ids に書かれた注文APIのURLに置き換えます。

orders-openapi.json
{
  "openapi": "3.0.1",
  "info": {"title": "Orders API", "version": "1.0"},
  "servers": [{"url": "<注文APIのURL>"}],
  "paths": {
    "/orders": {
      "get": {
        "operationId": "listOrders",
        "description": "サインイン中のユーザーの注文一覧を取得する",
        "responses": {"200": {"description": "注文一覧",
          "content": {"application/json": {"schema": {"type": "object"}}}}}
      },
      "post": {
        "operationId": "createOrder",
        "description": "注文を作成する",
        "requestBody": {"required": true, "content": {"application/json": {"schema": {
          "type": "object", "properties": {"item": {"type": "string"}}, "required": ["item"]}}}},
        "responses": {"201": {"description": "作成した注文",
          "content": {"application/json": {"schema": {"type": "object"}}}}}
      }
    }
  }
}
setup_agentcore.sh
set -euo pipefail
source .env.ids
export AWS_REGION
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
DISCOVERY_URL="https://cognito-idp.${AWS_REGION}.amazonaws.com/${POOL_ID}/.well-known/openid-configuration"
AGENT_CLIENT_SECRET=$(aws cognito-idp describe-user-pool-client --user-pool-id "$POOL_ID" \
  --client-id "$AGENT_CLIENT_ID" --query UserPoolClient.ClientSecret --output text)

# Cognito とトークン交換するカスタムプロバイダー(アクターは agent クライアントの M2M トークン)
aws bedrock-agentcore-control create-oauth2-credential-provider --cli-input-json "{
  \"name\": \"cognito-obo-provider\",
  \"credentialProviderVendor\": \"CustomOauth2\",
  \"oauth2ProviderConfigInput\": {\"customOauth2ProviderConfig\": {
    \"oauthDiscovery\": {\"discoveryUrl\": \"${DISCOVERY_URL}\"},
    \"clientId\": \"${AGENT_CLIENT_ID}\",
    \"clientSecret\": \"${AGENT_CLIENT_SECRET}\",
    \"clientAuthenticationMethod\": \"CLIENT_SECRET_BASIC\",
    \"onBehalfOfTokenExchangeConfig\": {
      \"grantType\": \"TOKEN_EXCHANGE\",
      \"tokenExchangeGrantTypeConfig\": {
        \"actorTokenContent\": \"M2M\",
        \"actorTokenScopes\": [\"agent/invoke\"]
      }
    }
  }}
}" > /dev/null

PROVIDER_ARN=$(aws bedrock-agentcore-control get-oauth2-credential-provider \
  --name cognito-obo-provider --query credentialProviderArn --output text)
SECRET_ARN=$(aws bedrock-agentcore-control get-oauth2-credential-provider \
  --name cognito-obo-provider --query clientSecretArn.secretArn --output text)
BASE="arn:aws:bedrock-agentcore:${AWS_REGION}:${ACCOUNT_ID}"

# Gateway のサービスロール
aws iam create-role --role-name obo-cognito-gateway-role --assume-role-policy-document "{
  \"Version\": \"2012-10-17\",
  \"Statement\": [{\"Effect\": \"Allow\",
    \"Principal\": {\"Service\": \"bedrock-agentcore.amazonaws.com\"},
    \"Action\": \"sts:AssumeRole\",
    \"Condition\": {\"StringEquals\": {\"aws:SourceAccount\": \"${ACCOUNT_ID}\"}}}]
}" > /dev/null
aws iam put-role-policy --role-name obo-cognito-gateway-role --policy-name obo-gateway --policy-document "{
  \"Version\": \"2012-10-17\",
  \"Statement\": [
    {\"Effect\": \"Allow\",
     \"Action\": [\"bedrock-agentcore:GetWorkloadAccessToken\", \"bedrock-agentcore:GetWorkloadAccessTokenForJWT\"],
     \"Resource\": [\"${BASE}:workload-identity-directory/default\",
                    \"${BASE}:workload-identity-directory/default/workload-identity/*\"]},
    {\"Effect\": \"Allow\", \"Action\": \"bedrock-agentcore:GetResourceOauth2Token\",
     \"Resource\": [\"${BASE}:token-vault/default\",
                    \"${BASE}:token-vault/default/oauth2credentialprovider/cognito-obo-provider\",
                    \"${BASE}:workload-identity-directory/default\",
                    \"${BASE}:workload-identity-directory/default/workload-identity/*\"]},
    {\"Effect\": \"Allow\", \"Action\": \"secretsmanager:GetSecretValue\", \"Resource\": \"${SECRET_ARN}\"}
  ]
}"
sleep 10

# Gateway(frontend クライアントが発行したトークンだけ受け付ける)
GATEWAY_ID=$(aws bedrock-agentcore-control create-gateway --name obo-cognito-gateway \
  --role-arn "arn:aws:iam::${ACCOUNT_ID}:role/obo-cognito-gateway-role" \
  --protocol-type MCP --authorizer-type CUSTOM_JWT \
  --authorizer-configuration "{\"customJWTAuthorizer\":{
    \"discoveryUrl\":\"${DISCOVERY_URL}\",
    \"allowedClients\":[\"${FRONT_CLIENT_ID}\"]}}" \
  --query gatewayId --output text)

echo "PROVIDER_ARN=$PROVIDER_ARN" >> .env.ids
echo "GATEWAY_ID=$GATEWAY_ID" >> .env.ids
tail -2 .env.ids

# 注文APIをツールとして登録し、呼び出す前にトークン交換する
source .env.ids
SCHEMA=$(uv run python -c "import json;print(json.dumps(open('orders-openapi.json').read()))")
aws bedrock-agentcore-control create-gateway-target --gateway-identifier "$GATEWAY_ID" --name orders \
  --target-configuration "{\"mcp\":{\"openApiSchema\":{\"inlinePayload\":${SCHEMA}}}}" \
  --credential-provider-configurations "[{
    \"credentialProviderType\": \"OAUTH\",
    \"credentialProvider\": {\"oauthCredentialProvider\": {
      \"providerArn\": \"${PROVIDER_ARN}\",
      \"scopes\": [\"orders-api/read\"],
      \"customParameters\": {
        \"audience\": \"orders-api\",
        \"subject_token_type\": \"urn:ietf:params:oauth:token-type:access_token\"},
      \"grantType\": \"TOKEN_EXCHANGE\"}}}]" > /dev/null

ユーザーのトークンを付けて、Gatewayのツールを呼び出してみます。

Gatewayを作成してツールを呼び出す
bash setup_agentcore.sh
set -a && source .env.ids && set +a
GATEWAY_URL=$(aws bedrock-agentcore-control get-gateway --gateway-identifier "$GATEWAY_ID" \
  --query gatewayUrl --output text)

curl -s -X POST "$GATEWAY_URL" -H "Authorization: Bearer $USER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"orders___listOrders","arguments":{}}}'
実行結果(textの中身を整形)
{
  "orders": [
    {"id": "A-1001", "item": "ノートPC", "status": "発送済み"},
    {"id": "A-1002", "item": "モニター", "status": "準備中"}
  ],
  "caller": {
    "username": "demo-user",
    "aud": "orders-api",
    "scope": "orders-api/read",
    "act": {"sub": "<agentクライアントのID>", "client_id": "<agentクライアントのID>", ...}
  }
}

Gateway経由でも注文一覧が返ってきました! 交換のコードを書かずに済みますね!

補足 AgentCore Runtimeから交換する

Gatewayも試しましたが、Runtimeで動かしているエージェントでもトークン交換したい・・・なんてケースありますよね。

Runtime上のエージェントのコードから交換するときはAgentCore SDKのデコレーターで交換の方式を指定します!
Runtimeがユーザーのトークンを検証し(インバウンド認証)、そのユーザーにひもづくトークンをコードに渡します。SDKはそれを使ってAgentCore Identityに交換を頼みます。

Cognitoと組み合わせるときは、Gatewayと同じく宛先とトークンの種類を指定します。入口では frontend クライアントのトークンを受け付けるようにしました。

Runtimeから交換する流れ。エージェントのコードがAgentCore Identityに交換を頼み、Cognitoで交換したトークンで注文APIを呼び出す

app/obo_agent/main.py
import os

import httpx
from bedrock_agentcore.identity.auth import requires_access_token
from bedrock_agentcore.runtime import BedrockAgentCoreApp

app = BedrockAgentCoreApp()
ORDERS_API_URL = os.environ["ORDERS_API_URL"]

# ユーザーのトークンを注文API宛てに交換(OBO)してから呼び出す
@requires_access_token(
    provider_name="cognito-obo-provider",
    auth_flow="ON_BEHALF_OF_TOKEN_EXCHANGE",
    scopes=["orders-api/read"],
    audiences=["orders-api"],
    custom_parameters={"subject_token_type": "urn:ietf:params:oauth:token-type:access_token"},
)
async def list_orders(*, access_token: str) -> dict:
    async with httpx.AsyncClient() as client:
        res = await client.get(f"{ORDERS_API_URL}/orders",
                               headers={"Authorization": f"Bearer {access_token}"})
        return {"status": res.status_code, "body": res.json()}

@app.entrypoint
async def invoke(payload, context):
    # 動作を見るため、モデルを通さずに注文APIを直接呼び出す
    return await list_orders()

if __name__ == "__main__":
    app.run()

ユーザーのトークンを付けてRuntimeを呼び出すと注文APIまで届きます!

Runtimeを呼び出した結果(抜粋)
{"status": 200, "body": {"orders": [...], "caller": {"username": "demo-user", "aud": "orders-api", "scope": "orders-api/read", "act": {"sub": "<agentクライアントのID>", "client_id": "<agentクライアントのID>", ...}}}}

デコレーターでそこまで難しくなく実装できましたね!
Gatewayのときと同じく、ユーザーの依頼を agent が代理で実行していることが注文APIに伝わっています。

Runtimeを作って呼び出す手順

このRuntimeはAgentCore CLI(0.28.1)で作り、テンプレートの使わないファイルは削除しました。設定ファイル(agentcore.json)には注文APIのURL用の環境変数と下のIAMポリシーを足しています。bedrock-agentcore は1.27.0です。

Runtimeを作って呼び出す
agentcore create --project-name CognitoObo --no-agent --skip-git
cd CognitoObo
agentcore add agent --name obo_agent --type create --language Python \
  --framework Strands --model-provider Bedrock --memory none \
  --authorizer-type CUSTOM_JWT \
  --discovery-url "https://cognito-idp.${AWS_REGION}.amazonaws.com/${POOL_ID}/.well-known/openid-configuration" \
  --allowed-clients "${FRONT_CLIENT_ID}"
# main.py・pyproject.toml・agentcore.json・obo-policy.json を書き換えてからデプロイ
agentcore deploy -y

RUNTIME_ARN=$(aws cloudformation describe-stacks --stack-name AgentCore-CognitoObo-default \
  --query "Stacks[0].Outputs[?contains(OutputKey,'RuntimeArn')].OutputValue" --output text)
ENCODED=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "${RUNTIME_ARN}")
curl -s -X POST \
  "https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/${ENCODED}/invocations?qualifier=DEFAULT" \
  -H "Authorization: Bearer ${USER_TOKEN}" \
  -H "Content-Type: application/json" \
  -H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: $(uuidgen)-$(uuidgen)" \
  -d '{"prompt": "注文一覧を見せて"}'
app/obo_agent/obo-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {"Effect": "Allow", "Action": "bedrock-agentcore:GetResourceOauth2Token",
     "Resource": ["arn:aws:bedrock-agentcore:us-east-1:<アカウントID>:token-vault/default",
                  "arn:aws:bedrock-agentcore:us-east-1:<アカウントID>:token-vault/default/oauth2credentialprovider/cognito-obo-provider",
                  "arn:aws:bedrock-agentcore:us-east-1:<アカウントID>:workload-identity-directory/default",
                  "arn:aws:bedrock-agentcore:us-east-1:<アカウントID>:workload-identity-directory/default/workload-identity/*"]},
    {"Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "<プロバイダーのシークレットのARN>"}
  ]
}

https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/on-behalf-of-token-exchange.html

後片付け

作成したリソースはGatewayから順に削除します。Runtimeを試したときは、先にスタックを削除します。

後片付けのコマンド
Runtimeを試したとき
aws cloudformation delete-stack --stack-name AgentCore-CognitoObo-default
後片付け
set -a && source .env.ids && set +a

TARGET_ID=$(aws bedrock-agentcore-control list-gateway-targets --gateway-identifier "$GATEWAY_ID" \
  --query "items[0].targetId" --output text)
aws bedrock-agentcore-control delete-gateway-target --gateway-identifier "$GATEWAY_ID" --target-id "$TARGET_ID"
sleep 10
aws bedrock-agentcore-control delete-gateway --gateway-identifier "$GATEWAY_ID"
aws bedrock-agentcore-control delete-oauth2-credential-provider --name cognito-obo-provider
aws iam delete-role-policy --role-name obo-cognito-gateway-role --policy-name obo-gateway
aws iam delete-role --role-name obo-cognito-gateway-role

aws apigatewayv2 delete-api --api-id "$API_ID"
aws lambda delete-function --function-name obo-orders-api
aws iam detach-role-policy --role-name obo-orders-api-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name obo-orders-api-role

aws cognito-idp delete-user-pool-domain --user-pool-id "$POOL_ID" --domain "$DOMAIN"
aws cognito-idp delete-user-pool --user-pool-id "$POOL_ID"

おわりに

Cognitoのトークン交換をAgentCore Gatewayと組み合わせて、OBOをサクッと試してみました。Cognitoでもトークン交換できるのは、最小権限を意識したいときやトークンの使い回しを防ぎたいときに嬉しいのではないでしょうか!

本記事が少しでも参考になりましたら幸いです。最後までご覧いただきありがとうございました!

この記事をシェアする

AWSのお困り事はクラスメソッドへ

関連記事