API Gateway(HTTP API)でJWTの検証を行う

API Gateway(HTTP API)でJWTの検証を行う

HTTP APIのJWTオーソライザーを利用してJWTの検証を行います。

HTTP API

HTTP APIを作成します。

JWTオーソライザー

作成したAPI(POST)に対してJWTオーソライザーを作成してアタッチします。

以下を入力します。

発行者:https://[YOUR-TENANT-NAME].jp.auth0.com/

対象者:API識別子(audience)

アタッチされると以下のようになります。

次にスコープ追加します。設定したスコープがJWTのクレームにあるか検証してくれます。

スコープ:read:users

テスト

前提:ユーザは、JWTオーソライザーで指定した対象者(audience)のread:usersパーミッションを持っている

curlでテストします。

異なるaudienceのJWT指定します。

$ curl -i -X POST \
  -H "Bearer: ey..." \
  https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/hoge
HTTP/1.1 401 Unauthorized
Date: Thu, 24 Aug 2023 21:43:04 GMT
Content-Type: application/json
Content-Length: 26
Connection: keep-alive
www-authenticate: Bearer scope="read:users" error="invalid_token" error_description="the token does not have a valid audience"
apigw-requestid: KL1ERgGgNjMEJ5a=

{"message":"Unauthorized"}

有効期限切れのJWTでテストします。

$ curl -i -X POST \
  -H "Bearer: ey..." \
  https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/hoge
HTTP/1.1 401 Unauthorized
Date: Thu, 24 Aug 2023 21:39:15 GMT
Content-Type: application/json
Content-Length: 26
Connection: keep-alive
www-authenticate: Bearer scope="read:users" error="invalid_token" error_description="the token has expired"
apigw-requestid: KL0gkhhqtjMEMCg=

{"message":"Unauthorized"}

正常なJWTでテストします。

$ curl -i -X POST \
  -H "Bearer: ey..." \
  https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/hoge
HTTP/1.1 200 OK
Date: Thu, 24 Aug 2023 21:41:11 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 20
Connection: keep-alive
Apigw-Requestid: KL0ypg5YNjMEJEQ=

"Hello from Lambda!"

正常なJWTで、一時的にAPI Gatewayのread:usersパーミッションをread:usersxxxに変更してテストします。

$ curl -i -X POST \
  -H "Bearer: ey..." \
  https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/hoge
HTTP/1.1 403 Forbidden
Date: Thu, 24 Aug 2023 21:52:40 GMT
Content-Type: application/json
Content-Length: 23
Connection: keep-alive
www-authenticate: Bearer scope="read:usersxxx" error="insufficient_scope" error_description="expected scopes: [read:usersxxx]"
apigw-requestid: KL2eTjeBNjMEP-Q=

{"message":"Forbidden"}

参考サイト

Choosing between REST APIs and HTTP APIs - Amazon API Gateway
Learn the differences between REST APIs and HTTP APIs.
JWT オーソライザーを使用した HTTP API へのアクセスの制御 - Amazon API Gateway
HTTP API の JWT 認証について説明します。

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました