(我已经审查了关于SO的类似问题,但是没有任何建议对我有用)
我有一个在Google App Engine(在Google Cloud Platform上)上运行的API服务。我需要通过Google Admin Directory API的身份验证,以便可以在GSuite域上创建组。
最初,我按照Obtaining and providing service account credentials manually的指南尝试了隐式授权,但我认为这可能仅限于在Google App Engine上运行的应用之间的通信。我的理解是,与App Engine外部的Google API进行通讯需要OAuth 2.0,因此我将其设置如下:
我已经设置了App Engine默认服务帐户,并且已经从Google Cloud Platform中向该帐户授予了域范围内的委派。通过遵循本指南-https://developers.google.com/admin-sdk/reports/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account
,我还从GSuite方面委派了整个域的权限我已经为服务帐户生成了P12密钥。然后,我将设置凭据,并使用它们来实例化Google Admin Directory客户端API,如下所示:
final List<String> SCOPES = Collections.singletonList(DirectoryScopes.ADMIN_DIRECTORY_GROUP);
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Email of the Service Account */
final String SERVICE_ACCOUNT_EMAIL = "my_service_account_email@appspot.gserviceaccount.com";
final String USER_EMAIL = "myGsuiteAdmin@mydomain.com";
/** Path to the Service Account's Private Key file */
final String SERVICE_ACCOUNT_PKCS12_FILE = "myPath.p12";
String p12Password = "notasecret";
ClassLoader classLoader = this.getClass().getClassLoader();
KeyStore keystore = KeyStore.getInstance("PKCS12");
InputStream keyFileStream = classLoader.getResourceAsStream(SERVICE_ACCOUNT_PKCS12_FILE);
if (keyFileStream == null){
throw new Exception("Key File Not Found.");
}
keystore.load(keyFileStream, p12Password.toCharArray());
PrivateKey pk = (PrivateKey)keystore.getKey("privatekey", p12Password.toCharArray());
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setServiceAccountUser(USER_EMAIL)
.setServiceAccountPrivateKey(pk)
.build();
Directory directory = new Directory.Builder(HTTP_TRANSPORT, JSON_FACTORY, null)
.setHttpRequestInitializer(credential).build();
com.google.api.services.admin.directory.model.Group group = new Group();
group.setEmail("test@mydomain.com");
group.setName("test_group");
group.setDescription("test_group_desc");
Group googleGroup = directory.groups().insert(group).execute();
// error on the line above (403: Not Authorized to access this resource/api - forbidden)
我在尝试创建新组的最后一行出现错误:
Group googleGroup = directory.groups().insert(group).execute();
403: Not Authorized to access this resource/api - forbidden
我需要怎么做才能成功进行身份验证?
答案 0 :(得分:3)
您的解决方案是遵循文档。