LoginSignup
1
1

More than 1 year has passed since last update.

Cognitoのtoken検証

Last updated at Posted at 2021-09-13

Cognitoログイン時に取得した、idToken 及び accessTokenの検証。
また、payloadを返却する。

事前準備

npm i --save jsonwebtoken jwk-to-pem

ロジック

  • 不正トークンや有効期限切れはこれで弾けるはず
import * as jwt from 'jsonwebtoken'
import * as jwkToPem from 'jwk-to-pem'

async decodeToken(token) {

    const decode =  jwt.decode(token, {complete: true})

    // 検証用のデータ取得
    // ここではhttp通信にnsetjsのライブラリ使っているが、取れればなんでも良い。
    const result = await this.httpService.get(`${decode.payload.iss}/.well-known/jwks.json`).toPromise()

    // kid一致したデータを取得
    const jwk = result.data.keys.find(key => {
      return key.kid === decode.header.kid
    })
    if (!jwk) {
      throw new Error("cognito's jwks is not found.")
    }

    const pem = jwkToPem(jwk);
        // 検証
    jwt.verify(token, pem, { algorithms: ['RS256'] }, function(err, decodedToken) {
      if (err) {
        throw err
      }
    });

    return decode.payload
  }

まとめ

Cognitoをtokenで毎回確認していれば不要かもって検証。
同時アクセスでCognioのクォータが引っかかりそうとかあれば、この辺りを使って工夫する必要あり。

参考

https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
https://qiita.com/FukuharaYohei/items/963b3ff293bf32062aa2

1
1
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
1
1