我试图从运行在上的Java应用程序中添加一个使用的组。我已经看了很多其他相关的问题,并尝试了一些建议,但我仍然得到了这个问题。
我使用Google控制台创建了一个新的服务帐户,并启用了G-Suite域范围的委托。我为服务帐户创建了一个JSON密钥。
我在Google控制台中启用了,对于该服务帐户的“客户机ID”,我随后在“安全性”>“高级设置”>“管理API客户端访问”下分配了Google控制台中的API范围。我正在分配范围https://www.googleapis.com/auth/admin.directory.group
在Google控制台中,我还在account > admin角色下将系统管理帐户设置为组Admin:
然后,在运行在Google上的Java应用程序中,我执行以下操作来使用服务帐户凭据来模拟我授予Group Admin权限的超级管理员用户:
final CREDENTIALS_FILE_PATH = "path_to_my_JSON_credentials_file"
final USER_EMAIL = "email_address_for_superadmin_with_group_admin_rights"
public someMethod() {
Directory directory = getDirectoryService(USER_EMAIL);
com.google.api.services.admin.directory.model.Group group = new Group();
group.setEmail("myemail@domain.com");
group.setName("test_group");
group.setDescription("test_group_desc");
Group googleGroup = directory.groups().insert(group).execute();
}
/**
* Build and returns a Directory service object authorized with the service accounts
* that act on behalf of the given user.
*
* @param userEmail The email of the user. Needs permissions to access the Admin APIs.
* @return Directory service object that is ready to make requests.
*/
public static Directory getDirectoryService(String userEmail) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
InputStream resourceAsStream = AdminService.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
Collection<String> scopeList = new ArrayList<>();
scopeList.add(DirectoryScopes.ADMIN_DIRECTORY_GROUP);
GoogleCredential gcFromJson = GoogleCredential.fromStream(resourceAsStream).createScoped(scopeList);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(gcFromJson.getTransport())
.setJsonFactory(gcFromJson.getJsonFactory())
.setServiceAccountId(gcFromJson.getServiceAccountId())
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKey(gcFromJson.getServiceAccountPrivateKey())
.setServiceAccountScopes(gcFromJson.getServiceAccountScopes())
.build();
Directory service = new Directory.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
在这条线上:
Group googleGroup = directory.groups().insert(group).execute();
我得到以下错误:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Not Authorized to access this resource/api",
"reason" : "forbidden"
} ],
"message" : "Not Authorized to access this resource/api"
}
我需要做些什么来验证身份?
发布于 2018-12-18 20:46:04
现在起作用了。导致403的问题之一是,我试图使用与该行中的GSuite域不匹配的域创建一个组:
group.setEmail("myemail@domain.com");
您可能还必须遵循此谷歌指南,才能访问第三方应用程序:
https://stackoverflow.com/questions/53843453
复制