无法使用服务帐户访问Google REST Api

时间:2018-12-13 11:57:40

标签: google-bigquery google-oauth2 google-authentication google-oauth-java-client

我需要使用Http客户端库通过服务帐户访问Google's BigQuery REST Api Endpoints。 因此,我尝试了文章Using OAuth 2.0 for Server to Server Applications

中提供的代码

它在下一行给了我编译错误。

Algorithm.RSA256(null,privateKey)

以下代码:

GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("service_account.json"));

    PrivateKey privateKey = credential.getServiceAccountPrivateKey();
    String privateKeyId = credential.getServiceAccountPrivateKeyId();

    try {

        Algorithm algorithm = Algorithm.RSA256(null, privateKey);

        String signedJwt = JWT.create().withKeyId(privateKeyId)
                .withIssuer("123456-compute@developer.gserviceaccount.com")
                .withSubject("123456-compute@developer.gserviceaccount.com")
                .withAudience("https://firestore.googleapis.com/google.firestore.v1beta1.Firestore")
                .withIssuedAt(new Date(now)).withExpiresAt(new Date(now + 3600 * 1000L)).sign(algorithm);
    } catch (Exception e) {
        e.printStackTrace();
    }

注意: Algorithm.RSA256()接受java.security.interfaces.RSAPrivateKey 而Google Api返回java.security.PrivateKey

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我发现对实现的了解:RSAPrivateKey继承自PrivateKey,因此,如果您将其强制转换(也许首先进行类型检查),那么您应该一切顺利!