
API Gateway REST API の JWT authorizer で Cognito と Firebase のトークンを検証してみた
はじめに
2026-11-17 に、API Gateway の REST API で JWT authorizer が使えるようになりました。
JWT authorizer を使うと、API Gateway がトークンの署名、issuer、audience、有効期限、claim を検証します。
この記事では、Cognito と Firebase Authentication のトークンを使って、JWT authorizer の動作を試しました。
検証の前提
検証用の構成
API は us-east-1、Cognito ユーザープールは ap-northeast-1 に作成しました。issuer にはユーザープールを 2 つ使いました。プール A がメインで、プール B は 2 つ目の issuer として、複数 issuer の節で追加しました。プール A にはリソースサーバー orders(スコープは read と write)を作りました。トークンに入るスコープ名は orders/read と orders/write です。アプリクライアントは 4 種類です。
| 名前 | 用途 | スコープ | authorizer の audiences |
|---|---|---|---|
| rw | クライアントクレデンシャルフロー | orders/read、orders/write | 作成時から入れる |
| ro | クライアントクレデンシャルフロー | orders/read | 作成時から入れる |
| other | クライアントクレデンシャルフロー | orders/read | 入れない |
| user | ユーザー認証(ID トークンとユーザーのアクセストークンを取得) | - | ID トークンの確認前に update-authorizer で追加 |
メソッドは次のとおりで、統合はすべて MOCK です。
- GET /orders(スコープ orders/read)
- POST /orders(スコープ orders/write)
- GET /open(スコープなし)
- GET /legacy(Cognito authorizer からの変換の確認用)
- GET /cog(Cognito authorizer との比較用)
プール B にも、リソースサーバー orders とアプリクライアント 1 つを同じ形で作りました。rw、ro、other のアクセストークンはクライアントクレデンシャルフローで取得し、有効期間は 5 分にしました。トークン要求の書き方は AWS Compute Blog に載っています。
Cognito 側の準備コマンド
aws cognito-idp create-user-pool --pool-name jwt-verify-pool-a
aws cognito-idp create-resource-server --user-pool-id ap-northeast-1_<POOL_ID> --identifier orders --name orders --scopes ScopeName=read,ScopeDescription=read ScopeName=write,ScopeDescription=write
aws cognito-idp create-user-pool-domain --user-pool-id ap-northeast-1_<POOL_ID> --domain <DOMAIN_PREFIX>
aws cognito-idp create-user-pool-client --user-pool-id ap-northeast-1_<POOL_ID> --client-name jwt-verify-a-rw --generate-secret --allowed-o-auth-flows client_credentials --allowed-o-auth-flows-user-pool-client --allowed-o-auth-scopes orders/read orders/write --access-token-validity 5 --token-validity-units AccessToken=minutes
aws cognito-idp create-user-pool-client --user-pool-id ap-northeast-1_<POOL_ID> --client-name jwt-verify-a-user --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH --id-token-validity 60 --token-validity-units IdToken=minutes
ro と other は、スコープを orders/read だけにして rw と同じ形で作成しました。
authorizer の作成
設定ファイル
設定項目の一覧は開発者ガイドにあります。
API Gateway は Cognito のアクセストークンの client_id を audiences と照合するので、audiences にはアプリクライアント ID を並べます。最初の設定を jwt-config.json として保存しました。
{
"issuers": [
{
"issuer": "https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>",
"audiences": [
"<CLIENT_ID_RW>",
"<CLIENT_ID_RO>"
]
}
],
"defaultAlgorithms": [
"RS256"
]
}
作成とメソッドへの紐付け
--type JWT を指定し、--jwt-configuration で設定ファイルを渡して authorizer を作成します。
aws apigateway create-authorizer --rest-api-id <API_ID> --region us-east-1 --name jwt-verify-authorizer --type JWT --identity-source method.request.header.Authorization --jwt-configuration file://jwt-config.json
メソッドには --authorization-type JWT と authorizer ID を指定します。--authorization-scopes を付けたメソッドは、そのスコープを持つトークンだけを通します。設定は create-deployment でステージに反映します。
aws apigateway put-method --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --authorization-type JWT --authorizer-id <AUTHORIZER_ID> --authorization-scopes orders/read
aws apigateway put-method --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method POST --authorization-type JWT --authorizer-id <AUTHORIZER_ID> --authorization-scopes orders/write
aws apigateway put-method --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --authorization-type JWT --authorizer-id <AUTHORIZER_ID>
aws apigateway create-deployment --region us-east-1 --rest-api-id <API_ID> --stage-name test
--resource-id には、/orders と /open それぞれのリソース ID を指定します。
MOCK 統合の準備
GET /orders の統合コマンドです。POST /orders は --http-method だけを変えて、同じ形で実行します。
aws apigateway put-integration --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --type MOCK --request-templates '{"application/json":"{\"statusCode\": 200}"}'
aws apigateway put-method-response --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --status-code 200
aws apigateway put-integration-response --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --status-code 200 --response-templates file://response-templates.json
response-templates.json は、メソッドと claims を応答本文に出すテンプレートです。
{
"application/json": "{\"method\":\"$context.httpMethod\",\"client_id\":$context.authorizer.claims.client_id,\"scope\":$context.authorizer.claims.scope,\"iss\":$context.authorizer.claims.iss,\"token_use\":$context.authorizer.claims.token_use}"
}
応答の確認
トークンごとの応答
issuer はプール A だけ、許可アルゴリズムは RS256 の設定で確認しました。ID トークンとユーザーのアクセストークンの行は、user クライアントを audiences に加えた後(jwt-config-v2.json)の結果です。リクエストは curl -i -H "Authorization: Bearer $TOKEN" https://<API_ID>.execute-api.us-east-1.amazonaws.com/test/<path> の形です。
| リクエスト | ステータス | error_description |
|---|---|---|
| rw のアクセストークンで GET /orders | 200 | - |
| rw のアクセストークンで POST /orders | 200 | - |
| ro のアクセストークンで GET /orders | 200 | - |
| ID トークンで GET /open | 200 | - |
| ro のアクセストークンで POST /orders | 403(insufficient_scope) | expected scopes within the token |
| ユーザーのアクセストークンで GET /orders | 403(insufficient_scope) | expected scopes within the token |
| トークンなし | 401 | -(www-authenticate は Bearer のみ) |
| 形式不正のトークン(abc.def.ghi) | 401 | the token is malformed |
| alg が none のトークン | 401 | the token is malformed |
| alg が HS256 のトークン | 401 | the token's signing algorithm is not allowed |
| 期限切れのトークン | 401 | the token has expired |
| audiences に入れていないクライアント(other)のトークン | 401 | the token does not have a valid audience |
| 未登録 issuer(プール B)のトークン | 401 | issuer does not match |
| ID トークンで GET /orders | 401 | the token's token_use is not valid for this method |
| アクセストークン(ユーザー、クライアントクレデンシャルとも)で GET /open | 401 | the token's token_use is not valid for this method |
Cognito が issuer の場合、スコープを指定したメソッドにはアクセストークンだけが通り、スコープを指定しないメソッドには ID トークンだけが通ります。
応答のヘッダと本文
拒否の理由は www-authenticate の error と error_description に入ります。本文の形は 401 と 403 で異なります。トークンなしの 401 は次のとおりです。
HTTP/2 401
x-amzn-errortype: UnauthorizedException
www-authenticate: Bearer
{"message":"Unauthorized"}
トークンを送って 401 になった場合は、www-authenticate ヘッダに error="invalid_token" と error_description が付きます。期限切れの応答は次のとおりです。本文のメッセージは、ほかの 401 の {"message":"Unauthorized"} とは異なりました。
HTTP/2 401
x-amzn-errortype: UnauthorizedException
www-authenticate: Bearer error="invalid_token" error_description="the token has expired"
{"message":"The incoming token has expired"}
スコープ不足の 403 には error="insufficient_scope" が付き、必要なスコープも www-authenticate に入ります。
HTTP/2 403
x-amzn-errortype: AccessDeniedException
www-authenticate: Bearer scope="orders/write" error="insufficient_scope" error_description="expected scopes within the token"
{"Message":"Access Denied"}
本文のキーは 401 が message、403 が Message で、先頭の大文字小文字が異なります。クライアントで本文を読んで分岐する場合は、両方を扱う必要があります。
有効期限
アクセストークンの有効期間は 5 分です。exp から 30 秒後と 40 秒後のリクエストは 200 のままで、75 秒後と 80 秒後は 401 になりました。
応答テンプレートで参照する claims
開発者ガイドは、統合から $context.authorizer.claims で claims を参照できると説明しています。
Cognito authorizer を設定した GET /cog を同じ API に作り、ro のトークンで JWT authorizer の GET /orders と応答を比べました。MOCK 統合の応答テンプレートでは、Cognito authorizer は claims の値が入りましたが、JWT authorizer は開発者ガイドの説明と異なり空でした。
Cognito authorizer(GET /cog):
{"method":"GET","client_id":<CLIENT_ID_RO>,"scope":orders/read,"iss":https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>,"token_use":access}
JWT authorizer(GET /orders):
{"method":"GET","client_id":,"scope":,"iss":,"token_use":}
設定の変更
update-authorizer による設定の置換
update-authorizer は設定全体を置き換えるので、一部だけを変える場合も設定全体を渡します。ただし、get-authorizer が返す jwtConfiguration には jwksUri が含まれており、これをそのまま渡すと次のエラーで拒否されました。
aws: [ERROR]: An error occurred (BadRequestException) when calling the UpdateAuthorizer operation: Invalid value for patch operation 'replace' and path '/jwtConfiguration'. The value should be the JWT configuration as JSON.
jwksUri を除いた設定ファイルなら更新できます。user クライアントを audiences に加えた jwt-config-v2.json で更新する例です。
{
"issuers": [
{
"issuer": "https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>",
"audiences": [
"<CLIENT_ID_RW>",
"<CLIENT_ID_RO>",
"<CLIENT_ID_USER>"
]
}
],
"defaultAlgorithms": [
"RS256"
]
}
aws apigateway update-authorizer --region us-east-1 --rest-api-id <API_ID> --authorizer-id <AUTHORIZER_ID> --patch-operations "$(jq -n --rawfile v jwt-config-v2.json '[{op:"replace",path:"/jwtConfiguration",value:$v}]')"
以降の設定変更も、ファイル名だけを替えたこの形のコマンドで行い、変更後に create-deployment を実行しました。デプロイ直後は、新旧どちらの設定による応答も返ってきました。たとえば次節でプール B を追加したときは、デプロイの約 1 分後も、B のトークンで POST /orders を呼ぶと旧設定の 401(issuer does not match)が返りました。
複数 issuer
issuers にプール B を加えた jwt-config-two-issuers.json で更新しました。B の audiences には、B のアプリクライアント ID を入れます。
{
"issuers": [
{
"issuer": "https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>",
"audiences": [
"<CLIENT_ID_RW>",
"<CLIENT_ID_RO>",
"<CLIENT_ID_USER>"
]
},
{
"issuer": "https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_B_ID>",
"audiences": [
"<CLIENT_ID_B>"
]
}
],
"defaultAlgorithms": [
"RS256"
]
}
B のトークンは GET /orders、POST /orders とも 200 でした。A の ro は GET が 200、POST が 403 でした。B を issuers から外して更新すると、B のトークンは 401(issuer does not match)になり、A の rw は 200 のままでした。
追加 claim
issuer ごとに、特定の claim が期待する値を持つことを条件にできます。ro の client_id を期待値にした jwt-config-additional-claims.json で試しました。
{
"issuers": [
{
"issuer": "https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>",
"audiences": [
"<CLIENT_ID_RW>",
"<CLIENT_ID_RO>",
"<CLIENT_ID_USER>"
],
"additionalClaims": [
{
"claimName": "client_id",
"format": "SINGLE_STRING",
"required": true,
"expectedValues": [
"<CLIENT_ID_RO>"
]
}
]
}
],
"defaultAlgorithms": [
"RS256"
]
}
client_id が期待値と一致しない rw のトークンで GET /orders を呼ぶと、403 になりました。www-authenticate ヘッダには error="insufficient_scope" error_description="the token does not satisfy the required claims" が付きます。一致する ro のトークンでは 200 でした。
claimName に scope を指定した更新は、次のエラーで拒否されました。
aws: [ERROR]: An error occurred (BadRequestException) when calling the UpdateAuthorizer operation: Invalid claim name: scope. Claim name should not be one of iss, aud, exp, nbf, iat, scope, scp.
署名アルゴリズム
defaultAlgorithms を ES256 だけにする更新は、update-authorizer の実行時に拒否されました。プール A の JWKS にある署名鍵は 2 つとも RS256 で、ES256 の鍵がないためです。
aws: [ERROR]: An error occurred (BadRequestException) when calling the UpdateAuthorizer operation: Invalid issuer: https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>. Issuer's JSON Web Key Set should have a signing key with a key ID for at least one of these algorithms: ES256.
Cognito authorizer からの変換
COGNITO_USER_POOLS 型の authorizer は、1 回の update-authorizer で JWT 型に変換できます。パッチは、type の置換、jwtConfiguration の置換、providerARNs の削除の 3 操作です。convert-patch-operations.json として保存しました。
[
{"op": "replace", "path": "/type", "value": "JWT"},
{"op": "replace", "path": "/jwtConfiguration", "value": "{\n \"issuers\": [\n {\n \"issuer\": \"https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>\",\n \"audiences\": [\n \"<CLIENT_ID_RW>\",\n \"<CLIENT_ID_RO>\",\n \"<CLIENT_ID_USER>\"\n ]\n }\n ],\n \"defaultAlgorithms\": [\n \"RS256\"\n ]\n}\n"},
{"op": "remove", "path": "/providerARNs", "value": "arn:aws:cognito-idp:ap-northeast-1:<ACCOUNT_ID>:userpool/ap-northeast-1_<POOL_ID>"}
]
aws apigateway update-authorizer --region us-east-1 --rest-api-id <API_ID> --authorizer-id <AUTHORIZER_ID> --patch-operations file://convert-patch-operations.json
変換時の update-authorizer 応答では、authType が cognito_user_pools のままでした(新規に作った JWT authorizer は jwt)。
変換してデプロイしても、GET /legacy の authorizationType は COGNITO_USER_POOLS のままでした。ro のトークンはデプロイの約 1 分半後も 401 でした。authorizationType は別途更新する必要があります。
aws apigateway update-method --region us-east-1 --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --patch-operations op=replace,path=/authorizationType,value=JWT
再デプロイ後、ro は 200 になりました。変換前の Cognito authorizer では other のトークンも 200 で通りましたが、変換後は audiences に入れていないため 401(the token does not have a valid audience)になります。トークンなしは変換の前後とも 401 です。移行する場合は、通したいアプリクライアントをすべて audiences に入れます。
Cognito 以外の issuer(Firebase Authentication)
トークンと issuer の設定
Google Cloud プロジェクトで Firebase Authentication の匿名認証を有効にし、API キーを発行しました。匿名サインアップで ID トークンを取得します。<API_KEY> は発行したキーに置き換えます。
curl -s -X POST -H 'Content-Type: application/json' -d '{"returnSecureToken":true}' "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=<API_KEY>"
応答の idToken が ID トークンです。ヘッダの alg は RS256 で、issuer の discovery 文書が示す署名アルゴリズムも RS256 でした。sub と user_id を除いたペイロードは次のとおりです。scope と scp は含まれていません。
{"provider_id":"anonymous","iss":"https://securetoken.google.com/<PROJECT_ID>","aud":"<PROJECT_ID>","auth_time":1795002572,"iat":1795002572,"exp":1795006172,"firebase":{"identities":{},"sign_in_provider":"anonymous"}}
この iss を 2 つ目の issuer、aud を audiences にして、Cognito のプール A と並べました。ファイル名は jwt-config-cognito-and-firebase.json です。
{
"issuers": [
{
"issuer": "https://cognito-idp.ap-northeast-1.amazonaws.com/ap-northeast-1_<POOL_ID>",
"audiences": [
"<CLIENT_ID_RW>",
"<CLIENT_ID_RO>",
"<CLIENT_ID_USER>"
]
},
{
"issuer": "https://securetoken.google.com/<PROJECT_ID>",
"audiences": [
"<PROJECT_ID>"
]
}
],
"defaultAlgorithms": [
"RS256"
]
}
メソッドと追加 claim の結果
| 設定 | リクエスト | ステータス | error_description |
|---|---|---|---|
| 上記の 2 issuer | Firebase のトークンで GET /open | 200 | - |
| 上記の 2 issuer | Firebase のトークンで GET /orders | 403(insufficient_scope) | expected scopes within the token |
| 上記の 2 issuer | Firebase のトークンで POST /orders | 403(insufficient_scope) | expected scopes within the token |
| 上記の 2 issuer | Cognito の ro のトークンで GET /orders | 200 | - |
| Firebase の issuer に追加 claim provider_id = anonymous | Firebase のトークンで GET /open | 200 | - |
| Firebase の issuer に追加 claim provider_id = google.com | Firebase のトークンで GET /open | 403(insufficient_scope) | the token does not satisfy the required claims |
| Firebase の audiences を別の値に変更 | Firebase のトークンで GET /open | 401 | the token does not have a valid audience |
今回の Firebase のトークンは scope を持たず、スコープ付きのメソッドでは 403 になりました。Firebase のトークンを通すメソッドにはスコープを指定せず、絞り込みは追加 claim で行います。
署名の検証
Firebase のトークンをもとに、次の 3 つを GET /open に送りました。
- 元のトークン
- ペイロードの provider_id を書き換え、署名は元のままにしたトークン
- 署名を別の値に差し替えたトークン
元のトークンは 200、改ざんした 2 つはどちらも 401(the token signature is invalid)でした。
まとめ
これまで、Firebase など Cognito 以外の ID プロバイダーのトークンを検証するには Lambda オーソライザーが必要で、検証のコードを書いて運用しなければなりませんでした。
API Gateway の REST API が JWT authorizer をサポートしたことで、トークン検証は設定だけで済むようになりました。
複数の ID プロバイダーのトークンを受け入れる必要があるマルチテナントの API などで、ご活用ください。








