获取来自Google凭据的applicationDefault

huangapple go评论78阅读模式
英文:

Fetching applicationDefault from GoogleCredentials

问题

我正在进行一个Java Spring项目,需要我将消息发布到Google Pub/Sub。我需要将访问令牌作为Authorization标头发送在POST请求中。
我尝试使用GoogleCredentials.getApplicationDefault(),但它要求在环境变量中设置GOOGLE_APPLICATION_CREDENTIALS。

这是我尝试的内容:

Map<String, String> env = System.getenv();
Field field = env.getClass().getDeclaredField("m");
field.setAccessible(true);

((Map<String, String>) field.get(env)).put("GOOGLE_APPLICATION_CREDENTIALS", "/etc/gcp/sa_credentials.json");

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
credentials.refreshIfExpired();

String accessToken = credentials.getAccessToken().toString();

当我尝试运行这个代码时,我收到以下错误消息:
java.io.IOException: Scopes not configured for service account. Scoped should be specified by calling createScoped or passing scopes to constructor

我不确定如何为服务帐户添加范围。是否有什么我遗漏的地方?

英文:

I am working on a java spring project which requires me to publish a message to Google Pub/Sub. I need to send the access token as an Authorization header in the post request.
I tried using GoogleCredentials.getApplicationDefault() but it requires GOOGLE_APPLICATION_CREDENTIALS to be set in the environmental variables.

Here is what I tried

Map&lt;String, String&gt; env = System.getenv();
Field field = env.getClass().getDeclaredField(&quot;m&quot;);
field.setAccessible(true);

((Map&lt;String, String&gt;) field.get(env)).put(&quot;GOOGLE_APPLICATION_CREDENTIALS&quot;, &quot;/etc/gcp/sa_credentials.json&quot;);

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
credentials.refreshIfExpired();

String accessToken = credentials.getAccessToken().toString();

When I try to run this, I get this error -
java.io.IOException: Scopes not configured for service account. Scoped should be specified by calling createScoped or passing scopes to constructor

I am not sure how to add scope for the service account. Is there anything I am missing?

答案1

得分: 2

创建一个作用域凭据,就像这样:

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
英文:

Simply create a scoped credential like this

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(&quot;https://www.googleapis.com/auth/cloud-platform&quot;));

huangapple
  • 本文由 发表于 2020年8月12日 01:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63363117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定