1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CognitoのJWTをNode.js(Typescript)で検証する方法

Posted at

JWT検証の実装

npm i jsonwebtoken jwks-rsa
npm i -D @types/jsonwebtoken
index.ts
import jwt, { JwtHeader, SigningKeyCallback } from "jsonwebtoken";
import jwksClient from "jwks-rsa";
var client = jwksClient({
  jwksUri:
    "https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json",
});

function getKey(header: JwtHeader, callback: SigningKeyCallback) {
  if (!header.kid) throw new Error("not found kid!");
  client.getSigningKey(header.kid, function (err, key) {
    if (err) throw err;
    callback(null, key.getPublicKey());
  });
}

const token = "{jwtToken}";

jwt.verify(token, getKey, function (err, decoded) {
  if (err) throw err;
  console.log(decoded);
});
npx ts-node index.ts

キャッシュについて

毎回Cognitoのjwksにアクセスしなくて良いように、デフォルトでキャッシュ有効になってます。便利!
https://github.com/auth0/node-jwks-rsa#caching

AmplifyでのJWTの取り方

import { Auth } from "aws-amplify";
.....
const session = await Auth.currentSession()
const jwt = session.getAccessToken().getJwtToken()
console.log(jwt);

JWTってJSON Web Tokenの略だから、このメソッド名Token被ってない!?

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?