Search code examples
google-directory-api

How to obtain user's organization name from Google APIs


Our app authenticates users with Google using OpenID connect, then attempts to obtain the name of the user's organization using Google's APIs, since it is not available in the Open ID Connect UserInfo object. The code is as follows:

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();

Although the user is returned, the value of organizations is null, even though the organization is defined in the Google Apps Admin panel. How does one obtain the company name of an authenticated Google user?


Solution

  • The following call retrieves customer info using Google Directory API:

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

    Note: Use of my_customer will retrieve current customer. At minimum, this call requires the following scope:

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

    It seems customer info cannot be obtained using a service credential. It needs to be a Client ID credential. The user logging in has to consent to the above scope.

                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();