3

I am trying to get an access token for Google Service Account. Following is my code -

String SERVICE_ACCOUNT_EMAIL = "edited@developer.gserviceaccount.com";
List scope = new ArrayList();
scope.add("https://www.googleapis.com/auth/admin.directory.user");
String keyFile = "C:\\edited-privatekey.p12";
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(scope)
.setServiceAccountPrivateKeyFromP12File(new java.io.File(keyFile))
.build();

credential.refreshToken();
String accessTokens = credential.getAccessToken();

Although the code works fine and I do get an access token, when I try to use it to 'GET' a Google Apps User using the Google Directory APIs, I get a 403 - Forbidden response code. Could someone please help?
I know the code for GET user is correct because it works fine with the access token generated by Google Apps Admin.

Sayali
  • 356
  • 1
  • 2
  • 13

3 Answers3

5

You need to set an admin account with:

.setServiceAccountUser(some_admin_email)

And make sure your App (with the correct scopes) is granted access in the cpanel.

Soviut
  • 88,194
  • 49
  • 192
  • 260
qtxo
  • 1,378
  • 12
  • 12
  • 1
    Thanks for your help. I am getting following error after adding setServiceAccount - Exception in thread "main" 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" } The API access and services is both ON (else the admin access token would not have worked). The scope accesses are also ON. Is there any other specific setting that I should turn ON? – Sayali Dec 09 '13 at 07:04
4

Proceed to https://admin.google.com . Login and add Security control if not exists from More Controls. Click on Security->Advance Settings->Manage ThirdParty OAuth Client Access and check that those scopes are added(comma separated) for your xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com service account id/client id.

Soviut
  • 88,194
  • 49
  • 192
  • 260
user3240209
  • 51
  • 1
  • 4
0

You have to enable the specific api before using it inside https://console.developers.google.com/ library, to make it work with your api key. watch the video https://www.youtube.com/watch?v=s_G5CnAu69M.

  • 1
    While linking off to external sources is fine, your answer should stand on its own even if the links were removed, or stop working at some point. Can you, at minimum, summarize the steps for enabling the API here? – Jeremy Caney May 07 '20 at 22:11