0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JWTの取得と検証

Posted at

概要

Amazon Cognito の User Pool の JSON ウェブトークン (JWT) を取得・検証してみた。
※ User Pool のみ使用。ID Pool は不要。無料で検証可。

JWTの取得

get-id-token.ts

Amazon Cognito の IDトークンは、JWTである (Understanding the identity (ID) token)。
まずは、そのIDトークンを取得する。

参考

Cognito User Pool

Cognitoにおいて、GUIでのユーザー作成は、「パスワードを強制的に変更」ステータスから「確認済み」への変更が面倒くさいため、AWS CLIからユーザーを作成する。

# ユーザーを作成
aws cognito-idp admin-create-user --user-pool-id "[COGNITO_USER_POOL_ID]" --username "[COGNITO_USER_NAME]" --user-attributes Name=email,Value="[COGNITO_USER_NAME]" Name=email_verified,Value=true --message-action SUPPRESS

# ユーザーのパスワードを変更
aws cognito-idp admin-set-user-password --user-pool-id "[COGNITO_USER_POOL_ID]" --username "[COGNITO_USER_NAME]" --password "[COGNITO_USER_PASSWORD]" --permanent

参考

その他参考

JWTの検証

jsonwebtokenを使用

  • JWT認証の流れを理解する

    • Amazon Cognito の JWT は、公開鍵方式 (秘密鍵で署名の作成、公開鍵で署名の検証) で署名されている。上記サイトIDプロバイダが、今回の場合は Amazon Cognito となる。
  • CognitoのJWTをNode.js(Typescript)で検証する方法

    • jsonwebtokenでJWTの検証を行っている。
      • jwt-verify を使用。
    • node-jwks-rsaで、 JWT の kid を基に公開鍵を取得。
      • 公開鍵は、 Amazon Cognitoの https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json (参考:Verifying a JSON Web Token) から取得できる。
  • Verifying a JSON Web Tokenでは、以下の検証を要求している。

    1. トークンは、有効期限切れではない
    2. IDトークンに含まれる aud クレームは、 App Client Id と一致している
      • option の audience に、Cognito の App Client Id を設定することで、 aud の検証を追加できる。
    3. IDトークンに含まれる issur クレーム (iss) は、 User Pool (https://cognito-idp.<region>.amazonaws.com/<userpoolID>) と一致している
      • option の issure に、Cognito の User Pool を設定することで、 issure の検証を追加できる。
    4. token_use クレームの確認 (IDトークンのみを使用する場合、IDトークンの token_use クレームが id になっている)
      • IDトークンのデコード結果は、 payload であり、その中に token_use があるので、チェックする。

AWS JWT Verifyを使用

その他参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?