如何以编程方式获取GCP Compute API的访问令牌

时间:2018-09-07 11:21:13

标签: google-app-engine google-compute-engine google-authentication

我需要一些有关GCP中访问令牌的帮助。我使用Java作为程序语言,并尝试了不同的方法,例如: https://cloud.google.com/iap/docs/authentication-howtohttps://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth

我正在使用第二种方法。代码段:

 String privateKeyId = "my-private-key";

    long now = System.currentTimeMillis();

    String signedJwt = null;

    try {
        Algorithm algorithm = Algorithm.RSA256(null, privateKey);
         signedJwt = JWT.create()
                .withKeyId(privateKeyId)
                .withIssuer("my-issuer")
                .withSubject("my-subject")
             .withAudience("https://www.googleapis.com/compute/v1/compute.machineTypes.list")
                .withIssuedAt(new Date(now))
                .withExpiresAt(new Date(now + 3600 * 1000L))
                .sign(algorithm);
    } catch (Exception e){
        e.printStackTrace();
    }

    return signedJwt;

然后我执行get实例,将返回的令牌设置为Bearer授权标头,但响应为:

 com.google.api.client.http.HttpResponseException: 401 Unauthorized
     {
     "error": {
     "errors": [
       {
       "domain": "global",
       "reason": "authError",
       "message": "Invalid Credentials",
       "locationType": "header",
       "location": "Authorization"
       }
       ],
       "code": 401,
    "message": "Invalid Credentials"
       }
       }

使用相同的凭据,我可以访问SDK。

谢谢!

1 个答案:

答案 0 :(得分:0)

根据@Dalmto,您应该使用Java客户端库。这是link入门指南。