Java 从GoogleCredentials获取applicationDefault

Java 从GoogleCredentials获取applicationDefault,java,spring,google-cloud-platform,google-authentication,Java,Spring,Google Cloud Platform,Google Authentication,我正在从事一个java spring项目,该项目要求我向Google Pub/Sub发布一条消息。我需要在post请求中将访问令牌作为授权头发送。 我尝试使用GoogleCredentials.getApplicationDefault(),但它要求在环境变量中设置GOOGLE\u APPLICATION\u凭据 这是我试过的 Map<String, String> env = System.getenv(); Field field = env.getClass().getDecl

我正在从事一个java spring项目,该项目要求我向Google Pub/Sub发布一条消息。我需要在post请求中将访问令牌作为授权头发送。 我尝试使用GoogleCredentials.getApplicationDefault(),但它要求在环境变量中设置GOOGLE\u APPLICATION\u凭据

这是我试过的

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();
Map env=System.getenv();
Field=env.getClass().getDeclaredField(“m”);
字段。setAccessible(true);
((Map)field.get(env)).put(“GOOGLE_APPLICATION_CREDENTIALS”,”/etc/gcp/sa_CREDENTIALS.json);
GoogleCredentials=GoogleCredentials.getApplicationDefault();
credentials.refreshIfExpired();
String accessToken=credentials.getAccessToken().toString();
当我试着运行这个时,我得到了这个错误-
java.io.IOException:未为服务帐户配置作用域。应通过调用createScoped或将作用域传递给构造函数来指定作用域


我不确定如何为服务帐户添加作用域。有什么我遗漏的吗?

只需创建一个像这样的作用域凭证

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