解析 Auth0 JWT Claims 时遇到的一些问题

Some troubles while parsing Auth0 JWT Claims

public Map<String, String> verifyToken(final String token) throws NoSuchAlgorithmException, InvalidKeySpecException {
    final Algorithm algorithm = Algorithm.RSA256(getPublicKey());
    final JWTVerifier verifier = JWT.require(algorithm).withIssuer(tokenConfiguration.getIssuer()).build();

    try {
        final DecodedJWT decodedJWT = verifier.verify(token);
        return decodedJWT.getClaims().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().toString()));
    } catch (final JWTVerificationException jwtVerificationException) {
        throw new RuntimeException();
    }
}

我有这段代码,它基本上验证令牌并将声明检索为 HashMap

final String phone = Optional
        .ofNullable(claimMap.get("phone"))
        .orElseThrow(() -> new RuntimeException());

当我尝试从 Hashmap 中获取 phoneNumber 时,它 return 正确 phone 但 ""+1231551921"" 错误。如何去掉多余的引号?

我的问题是如何以正确的方式解析 JWT 声明?

我的带有 RSA-256 的 jwt 令牌:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6IjA1MzgqKio3NSoqIiwiaXNzIjoidGVzdC5jb20iLCJleHAiOjE2NDkyNTM5ODcsImp0aSI6InJlZnJlc2hfdG9rZW4ifQ.SbLRBFCjaePFu8kjmYRrBfj6iHWBJoLzABwD2d8vxIQlEM2ZZXzJ9wUCu_MiIZ7B6M5k4aRtjdg4TDEJ3HvwnAQMl63P5C46iKaDmmhg4-hx0M_alwo8f5iDuQ2BAInPiPVo4qjFQQqN_Yti0qfW2amGGwvA5yTXK1D4NONR6B7CPY1SrqPgnZ9Q2zZv039SxbsdQTtZ2u80sA2b8kmAoK69NZt6PadSFRjdXy-VMzuG5HitSvtP4xLplFGfvptHg0DrNeGEy4daqofbBXYybPbPi0VQ3mxSjYaK2EIOFOm2FJDISQ_7sZXy6pwOYepKR5CfNAzRskM_Tpf6G2Nt9g

问题出在这一行:

return decodedJWT.getClaims().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().toString()));

字典值是Claim个实例,Claim个实例基本上是JSON的片段,所以它们可以是数字、字符串、数组或字典。

如果调用泛型 toString() 方法,结果的格式将被设置为可以安全区分类型,例如:

  • 37 一个数字
  • "+1231551921" 对于字符串
  • [ 37, "+1231551921" ] 对于数组

如果您确定您的声明是字符串类型,请调用 asString() 而不是 toString()