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
被ってない!?