JWT検証の実装
npm i jsonwebtoken jwks-rsa
npm i -D @types/jsonwebtoken
index.ts
importjwt,{JwtHeader,SigningKeyCallback}from"jsonwebtoken";importjwksClientfrom"jwks-rsa";varclient=jwksClient({jwksUri:"https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json",});functiongetKey(header:JwtHeader,callback:SigningKeyCallback){if(!header.kid)thrownewError("not found kid!");client.getSigningKey(header.kid,function(err,key){if(err)throwerr;callback(null,key.getPublicKey());});}consttoken="{jwtToken}";jwt.verify(token,getKey,function(err,decoded){if(err)throwerr;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";.....constsession=awaitAuth.currentSession()constjwt=session.getAccessToken().getJwtToken()console.log(jwt);
JWTってJSON Web Token
の略だから、このメソッド名Token
被ってない!?