I can't seem to be able to utilize the Google API with Oauth. What am I missing?
Error Message:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_scope",
"error_description" : "Invalid oauth scope or ID token audience provided."
}
Java code:
private void printLabels() {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
List<String> scopes = new ArrayList<>();
scopes.add(GmailScopes.GMAIL_LABELS);
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("C:\\test\\credential.json"));
credential.createScoped(scopes);
credential.refreshToken(); // error happens here
String appName = "VS";
Gmail.Builder builder = new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(appName);
Gmail gmail = builder.build();
Object o = gmail.users().labels().list("me").execute();
System.out.println("o = " + o);
}
Google API Configuration:
In my case I was having that issue using Python default()
to get the default credentials. It worked fine for the credentials loaded with gcloud auth application-default login
or Kubernetes Workload Identity. But when using a Service Account file with GOOGLE_APPLICATION_CREDENTIALS
I was having this issue when trying to call credentials.refresh()
. I fixed the issue by explicitly providing the scopes
parameter to default()
function with the ['https://www.googleapis.com/auth/cloud-platform']
scope.
So I changed from this:
from google.auth import default
credentials, _ = default()
To this:
from google.auth import default
credentials, _ = default(scopes=['https://www.googleapis.com/auth/cloud-platform'])