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

Viewed 10047

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)
1 Answers

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);
Related