Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting invalid_scope when attempting to obtain a refresh token via the Google API

Tags:

java

oauth

gmail

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:

  1. Logged in to https://console.developers.google.com/
  2. Created project
  3. Enabled Gmail API
  4. Created Service Account (assigned owner role)
  5. Download json credentials file
  6. Enabled OAuth consent screen - internal (not sure I need this since I only want to access my emails)
  7. Enabled service account domain wide delegation (not sure I need this either)
like image 229
Johan Avatar asked Nov 16 '25 02:11

Johan


2 Answers

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'])
like image 160
Mauricio Avatar answered Nov 18 '25 17:11

Mauricio


credential.createScoped(scopes)

Returns a copy of credential object with the given scope. You can verify this by credential.getServiceAccountScopes() and check if the scope is set.

Try assigning the value to credential object, like.

credential = credential.createScoped(scopes);
like image 28
Mukul Sethi Avatar answered Nov 18 '25 16:11

Mukul Sethi