Search code examples
javaoauthgmail

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


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)

Solution

  • 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'])