【问题标题】:Google API -> Unable to obtain access token from JWTGoogle API -> 无法从 JWT 获取访问令牌
【发布时间】:2020-06-12 09:56:37
【问题描述】:

我想使用从服务器生成的帐户服务令牌调用 Google API Analytics。

我按照link的指南进行操作

这是我生成签名 JSON Web 令牌的代码:

    final GoogleCredential credential = GoogleCredential.fromStream(JWTSample.class.getResourceAsStream ("/account_secrets.json"))
            .createScoped(List.of(
                    "https://www.googleapis.com/auth/analytics",
                    "https://www.googleapis.com/auth/analytics.readonly")
            );
    final PrivateKey privateKey = credential.getServiceAccountPrivateKey();
    final String privateKeyId = credential.getServiceAccountPrivateKeyId();
    try {

        long now = System.currentTimeMillis();

        Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
        String signedJwt = JWT.create()
                .withKeyId(privateKeyId)
                .withIssuer("test-295@symbolic-folio-268713.iam.gserviceaccount.com")
                .withAudience("https://oauth2.googleapis.com/token")
                .withIssuedAt(new Date(now))
                .withExpiresAt(new Date(now + 3600 * 1000L))
                .sign(algorithm);
        System.out.println(signedJwt);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

输出是一个签名的 JWT。

当我调用 Oauth2 服务从签名的 JWT 生成 access_token 时

 curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=<signed_JWT>' https://oauth2.googleapis.com/token

我收到此错误:

{
    "error": "invalid_scope",
    "error_description": "Invalid oauth scope or ID token audience provided."
}

有什么提示吗?

【问题讨论】:

    标签: google-api jwt google-oauth jwt-auth


    【解决方案1】:

    使用echo "${SIGNED_JWT}" | cut -d. -f2 | base64 --decode 解码JWT 断言声明集,您会看到没有scope 属性。

    GoogleCredential 实例具有范围,但它们没有被传递给 JWT 构建器。

    JWT.create() 之后使用此附加方法添加范围:

    .withClaim("scope", credential.getServiceAccountScopesAsString())
    

    【讨论】:

    • 如果没有你的帮助,我永远不会做到这一点。非常感谢(再次对谷歌文档感到羞耻)
    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2018-01-08
    • 2015-02-11
    • 1970-01-01
    • 2013-03-25
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多