英文:
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<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();
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("https://www.googleapis.com/auth/cloud-platform"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论