const jwt = require('jsonwebtoken'); // JS Lib used to verify JWTs
const jwksClient = require('jwks-rsa'); // JS Lib to get keys from a URL
const USER_POOL_ID = "<YOUR_USER_POOL_ID>";
const CLIENT_ID = "<YOUR_CLIENT_ID>";
const REGION = "<YOUR_REGION>";
const ISSUER_URI = "https://cognito-idp." + REGION + ".amazonaws.com/" + USER_POOL_ID;
const JWKS_URI = ISSUER_URI + "/.well-known/jwks.json";
// Generate a client to read keys from the Cognito public URL
let client = jwksClient({
jwksUri: JWKS_URI,
});
// Async function to get public keys from key Id in jwks.json
function getKey(header, callback) {
client.getSigningKey(header.kid, (err, key) => {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
// Verify jwt. getKey function will take the header from your idToken and get
the corresponding public key. This public key will be used by jwt.verify() to
actually verify the token.
jwt.verify(idToken, getKey, { audience: CLIENT_ID, issuer: ISSUER_URI }, function(err, decoded) {
console.log("RES", err, decoded);
// Additional verifications like token expiry can be done here.
}
1 回答
这个AWS Blog post详细解释了解决方案 .
Amazon Cognito生成的ID令牌和访问令牌是JWT . Cognito使用两个RSA密钥对来生成这些令牌 . 每对的私钥用于对令牌进行签名 . 公钥可用于验证令牌 . 这些公钥可在以下网址找到
使用此路径中的密钥ID,您需要获取公钥 . 使用此公钥,您可以验证令牌 .
以下是一个NodeJS代码片段,用于实现上述逻辑 . 完整的例子可以在this commit看到