我试图让google admin api调用用户使用服务帐户和JSON Key文件从java代码。
但我还是得到了错误。
Unknown Exception : com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
PUT https://www.googleapis.com/admin/directory/v1/users/[email protected]
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Not Authorized to access this resource/api",
"reason" : "forbidden"
} ],
"message" : "Not Authorized to access this resource/api"
}
我一直在尝试从一些时间,现在...请帮助这里是代码 - 。
GoogleCredentials credentials;
try (FileInputStream serviceAccountStream = new FileInputStream(CREDENTIALS_FILE_PATH)) {
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
}
List < String > scopes = new ArrayList < String > ();
scopes.add("https://www.googleapis.com/auth/admin.directory.user");
credentials = credentials.createScoped(scopes);
// Build a new authorized API client service.
//final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/*Directory service = new Directory.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();*/
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
/*Directory service = new Directory.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
.setApplicationName(APPLICATION_NAME)
.build();*/
Directory service = new Directory.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), requestInitializer).setApplicationName "APPLICATION_NAME").build();
User user = new User();
user.setSuspended(true);
user.setSuspensionReason("Worker on Leave");
Directory.Users.Update result = null;
result = service.users().update(workerEmailId, user);
user = result.execute();
if (user == null || user.size() == 0) {
System.out.println("No user updated.");
} else {
System.out.println("User:");
System.out.println(user.getName().getFullName());
System.out.println("User Status for Suspension :");
System.out.println(user.getSuspended());
}
}
如果服务账号要代为管理,则需
通过设置被冒充的用户,将服务账户冒充为管理员。
在java中,你需要建立一个GoogleCredential,指定了 ServiceAccountId
, PrivateKey
和 ServiceAccountUser
.
样本来自 文件:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
.setServiceAccountScopes(Collections.singleton(YOUR SCOPE))
.setServiceAccountUser("EMAIL OF THE ADMIN")
.build();