0
votes

I have been struggling with this for over a week.

I'm trying to write backend code in Java to manage users (create/add/delete) in my domain.

I keep seeing the following error:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Not Authorized to access this resource/api",
    "reason" : "forbidden"
  } ],
  "message" : "Not Authorized to access this resource/api"
}

I have been using the recommended Google Client API for Java. I have done the usual:

  1. Created service account
  2. Performed Domain wide delegation on the service account with the following scope - https://www.googleapis.com/auth/admin.directory.user
  3. Enabled the admin api on the project
  4. Written the code below (read somewhere that the JSON credential file doesn't work without the following hack)
GoogleCredential gcFromJson = GoogleCredential.fromStream(new FileInputStream(CREDENTIALS_FILE_PATH),httpTransport, JSON_FACTORY).createScoped(scopes);
GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(gcFromJson.getTransport())
        .setJsonFactory(gcFromJson.getJsonFactory())
        .setServiceAccountId(gcFromJson.getServiceAccountId())
        .setServiceAccountPrivateKey(gcFromJson.getServiceAccountPrivateKey())
        .setServiceAccountScopes(gcFromJson.getServiceAccountScopes())
        .build();

//credential.refreshToken();

Directory directory = new Directory.Builder(httpTransport, JSON_FACTORY, null)
    .setApplicationName("My App Name")
    .setHttpRequestInitializer(credential)
    .build();

User user = new User();
// populate are the required fields only
UserName name = new UserName();
name.setFamilyName("Blogs");
name.setGivenName("Jo");
user.setName(name);
user.setPassword("password101");
user.setPrimaryEmail("jo.blogs@<my actual domain>.org");
user.setEmails("jo.blogs@<my actual domain>.org");

// requires DirectoryScopes.ADMIN_DIRECTORY_USER scope
user = directory.users().insert(user).execute();
return user

Please, somebody, anybody help!

1
You might want to cleanup your question's code so everybody can read it. - John Hanley
Apologies and many thanks to the moderator who cleaned it up. I wanted to add that I added my superadmin user as a User Management Admin and am setting the service account user to that email address. I get a different error - 401 Unauthorized - thrown from Credential.refreshToken() in the insert(user).execute() operation. I see you helped @Chris Halcrow with a similar problem. I'm hoping you can give me a few pointers on how to proceed. I'm using the Compute Engine and not the AppEngine. - Danny

1 Answers

0
votes

There is one suggested way to create a simple Java command-line application that makes requests to the Directory API. Did you follow all these steps? Java Quickstart