【问题标题】:Fetching applicationDefault from GoogleCredentials从 GoogleCredentials 获取 applicationDefault
【发布时间】:2020-12-01 09:51:45
【问题描述】:

我正在开发一个 java spring 项目,该项目要求我将消息发布到 Google Pub/Sub。我需要在发布请求中将访问令牌作为授权标头发送。 我尝试使用 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

我不确定如何为服务帐户添加范围。我有什么遗漏吗?

【问题讨论】:

    标签: java spring google-cloud-platform google-authentication


    【解决方案1】:

    像这样简单地创建一个范围凭证

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2022-11-08
      • 2018-07-02
      • 2018-08-05
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多