Google Admin API - Service Account withJSON - 403 Forbidden error(禁止的错误)

问题描述 投票:0回答:1

我试图让google admin api调用用户使用服务帐户和JSON Key文件从java代码。

  1. 该服务帐户已启用全域授权。
  2. 客户端ID是授权的范围 - https:/www.googleapis.comauthadmin.directory.user

但我还是得到了错误。

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());
}
}
google-admin-sdk
1个回答
0
投票
  • 目录API只能由管理员使用。
  • 服务账户不是管理员
  • 如果服务账号要代为管理,则需

    • 启用G Suite全域授权(如您已经做的那样)。
    • 通过设置被冒充的用户,将服务账户冒充为管理员。

    • 在java中,你需要建立一个GoogleCredential,指定了 ServiceAccountId, PrivateKeyServiceAccountUser.

样本来自 文件:

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();
© www.soinside.com 2019 - 2024. All rights reserved.