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:
- Created service account
- Performed Domain wide delegation on the service account with the following scope - https://www.googleapis.com/auth/admin.directory.user
- Enabled the admin api on the project
- 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!