【问题标题】:How to get access token programatically for GCP Compute API如何以编程方式获取 GCP Compute API 的访问令牌
【发布时间】:2019-02-12 17:55:55
【问题描述】:

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

我正在使用第二种方法。代码sn-p:

 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。

谢谢!

【问题讨论】:

  • 请记住,服务帐户的代码与 Oauth2 的代码不同,创建的客户端也不同。
  • 感谢您的回复。这就是我想要弄清楚的。如何通过服务帐户检索访问令牌?
  • 您应该使用 java 客户端库,它会更容易,并且返回的用户凭据将具有您可以使用的访问令牌
  • 您已标记 App Engine 和 Compute Engine。答案可能会有所不同。您的代码实际托管在哪个平台上?
  • 我的平台是 Compute Engine。

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


【解决方案1】:

根据@DalmTo,您应该使用 Java 客户端库。这是link 让您开始使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多