如何从Google API

时间:2018-01-27 05:51:10

标签: google-directory-api

我们的应用使用OpenID connect对Google用户进行身份验证,然后尝试使用Google的API获取用户组织的名称,因为它在Open ID Connect UserInfo对象中不可用。代码如下:

JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleCredential credential = getCredentials(jsonFactory, httpTransport, connection.getDomainAdminEmail());
Directory directory = new Directory.Builder(httpTransport, jsonFactory, null).setApplicationName(APP_NAME).setHttpRequestInitializer(setHttpTimeout(credential)).build();
User user = directory.users().get(id).execute();
Object organizations = user.getOrganizations();

虽然返回了用户,但组织的值为空,即使组织是在Google Apps管理员面板中定义的。如何获取经过身份验证的Google用户的公司名称?

1 个答案:

答案 0 :(得分:0)

以下调用使用Google Directory API检索客户信息:

 directory.customers().get("my_customer").execute();

注意:使用my_customer将检索当前客户。此调用至少需要以下范围:

https://www.googleapis.com/auth/admin.directory.customer.readonly

似乎无法使用服务凭证获取客户信息。它必须是客户端ID凭据。登录的用户必须同意上述范围。

            GoogleCredential credential = getCredentials(jsonFactory, httpTransport, connection.getDomainAdminEmail(),true);

            Directory directory = new Directory.Builder(httpTransport, jsonFactory, null)
                .setApplicationName(APP_NAME)
                .setHttpRequestInitializer(setHttpTimeout(credential))
                .build();
                Customer customer = directory.customers().get("my_customer").execute();
                CustomerPostalAddress postAddress = customer.getPostalAddress();

            googleCustomer = new GoogleCustomer.Builder()
                .setPhoneNumber(customer.getPhoneNumber())
                .setLanguage(customer.getLanguage())
                .setCompany(postAddress.getOrganizationName())
                .setAddress1(postAddress.getAddressLine1())
                .setAddress2(postAddress.getAddressLine2())
                .setAddress3(postAddress.getAddressLine3())
                .setAddressContactName(postAddress.getContactName())
                .setAddressCountryCode(postAddress.getCountryCode())
                .setAddressLocality(postAddress.getLocality())
                .setAddressPostalCode(postAddress.getPostalCode())
                .setAddressRegion(postAddress.getRegion())
                .build();