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?
Simply create a scoped credential like this
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));