Requested scopes not allowed

2019-08-28 01:48发布

问题:

I'm trying to fetch a user from Google Directory API with the following request:

Collection<String> SCOPES = Arrays.asList("https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.user");
URL url = getClass().getResource("privatekey.p12");
GoogleCredential credential = new GoogleCredential.Builder()
    .setJsonFactory(request.getJsonFactory())
    .setServiceAccountId("foobar.com")
    .setServiceAccountScopes(SCOPES)
    .setTransport(new NetHttpTransport())
    .setServiceAccountUser("foo@bar.com")
    .setServiceAccountPrivateKeyFromP12File(new File(url.getPath())).build();
Directory dir = new Directory.Builder(GoogleNetHttpTransport.newTrustedTransport(), request.getJsonFactory(), credential)
    .setApplicationName(request.getApplicationName())
    .build();

But I'm getting the following error from the API:

Caused by: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "access_denied",
  "error_description" : "Requested scopes not allowed: https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly"
}

I've checked the scopes are correct, anyone know what's the problem here?

回答1:

Try using one scope or the other. If you only need read access, use the readonly scope. If you need read/write access to users, use the other.

Also, ensure that you've granted the service account's client_id access to these scopes in the Admin's control panel (admin.google.com) and that your ServiceAccountUser is a super admin in the domain.



回答2:

Argh! I removed the old service account and created a new one. After that things started to roll. Guessing I had a wrong p12 file etc. Can finally breathe again, phew.