AWS Cognito JWT令牌验证

时间:2017-09-26 14:57:45

标签: spring amazon-web-services spring-boot jwt amazon-cognito

我正在尝试基于AWS Cognito JWT令牌强制执行安全性,源代码位于https://github.com/IxorTalk/ixortalk.aws.cognito.jwt.security.filter

但我有疑虑,这是根据文件http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-identity-user-pools-using-id-and-access-tokens-in-web-api

它表示“ID令牌在用户进行身份验证后一小时到期。您应该在客户端或Web API过期后处理ID令牌。”

我在日志中看到的错误是哪个, com.nimbusds.jwt.proc.BadJWTException:已过期的JWT。我假设,JWT令牌已经过期,我成功实施基于令牌的授权的步骤是什么?

2 个答案:

答案 0 :(得分:0)

您需要刷新令牌,以帮助您获取新身份和访问令牌。 Cognito JS SDK会自动刷新令牌。

现在在您的情况下,您似乎需要调用RefreshToken并添加一个检查以查看令牌是否已过期。

身份/访问令牌带有到期时间,因此您可以在使用它们之前在应用程序中进行本地操作。

答案 1 :(得分:0)

如果您使用的是Java,我编程的方式就是这样

fragment()

我正在使用此存储库来验证和解析令牌,

fragment()

确保要导入以下内容,

    // Parse the Cognito Keys and get the key by kid
    // Key is just a class that is used for parsing JSON to POJO
    Key key = this.keyService.getKeyByKeyId(JWT.decode(token).getKeyId());

    // Use Key's N and E
    BigInteger modulus = new BigInteger(1, Base64.decodeBase64(key.getN()));
    BigInteger exponent = new BigInteger(1, Base64.decodeBase64(key.getE()));

    // Create a publick key
    PublicKey publicKey = null;
    try {
        publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
    } catch (InvalidKeySpecException e) {
        // Throw error
    } catch (NoSuchAlgorithmException e) {
        // Throw error
    }

    // get an algorithm instance
    Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) publicKey, null);

    // I verify ISS field of the token to make sure it's from the Cognito source
    String iss = String.format("https://cognito-idp.%s.amazonaws.com/%s", REGION, POOL_ID);

    JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer(iss)
            .withClaim("token_use", "id") // make sure you're verifying id token
            .build();

    // Verify the token
    DecodedJWT jwt = verifier.verify(token);

    // Parse various fields
    String username = jwt.getClaim("sub").asString();
    String email = jwt.getClaim("email").asString();
    String phone = jwt.getClaim("phone_number").asString();
    String[] groups = jwt.getClaim("cognito:groups").asArray(String.class);

如果令牌已过期,它将不会被更改。