AWS Cognito什么是验证客户端发送到我的应用程序的ID和访问令牌的方法

时间:2018-08-27 09:27:35

标签: amazon-web-services aws-cognito

我已经在cognito中创建了一个用户池,登录到我的应用程序后,我将从AWS Cognito生成的三个令牌存储在会话中。

我需要将这些令牌传递给第三方API,它们将作为响应将响应以及发送的令牌发送给我。

如何仅使用用户池ID和客户端应用ID来验证令牌。

1 个答案:

答案 0 :(得分:3)

AWS Blog post详细说明了解决方案。

Amazon Cognito生成的ID令牌和访问令牌是JWT。 Cognito使用两个RSA密钥对来生成这些令牌。每对的私钥用于对令牌进行签名。公用密钥可用于验证令牌。这些公用密钥位于

  

https:// cognito-idp。{REGION} .amazonaws.com / {YOUR_USER_POOL_ID} /.well-known/jwks.json

使用此路径中的密钥ID,您需要获取公共密钥。使用此公钥,您可以验证令牌。

以下是实现上述逻辑的NodeJS代码段。完整示例参见this commit

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.
}