【发布时间】:2019-02-12 17:55:55
【问题描述】:
我需要一些有关 GCP 中访问令牌的帮助。我使用 Java 作为程序语言,并尝试了不同的方法,例如: https://cloud.google.com/iap/docs/authentication-howto 和https://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