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

问题描述 投票:1回答:1

我需要一些帮助来访问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。

谢谢!

google-app-engine google-compute-engine google-authentication
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.