google-directory-apigoogle-people-api

How can I get the data of the domain users using a service account?


I am developing a corporate application in which we use the People API Directory APi, however, I always need to auto-check from a specific user, since I cannot receive data using a service account. How can I get the data of the domain users using a service account?


Solution

  • I used this code for connection google API.

    public class DirectoryService {
    @Value("${service.account.email}")
    private String SERVICE_ACCOUNT_EMAIL;
    @Value("${service.account.pk.file.path}")
    private String SERVICE_ACCOUNT_PKCS12_FILE_PATH;
    
    public Directory getDirectoryService(String userEmail){
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        Directory service = null;
        try {
            GoogleCredential credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                    .setServiceAccountScopes(Collections.singleton(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY))
                    .setServiceAccountUser(userEmail)
                    .setServiceAccountPrivateKeyFromP12File(
                            new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
                    .build();
            service = new Directory.Builder(httpTransport, jsonFactory, null)
                    .setHttpRequestInitializer(credential).build();
        } catch (GeneralSecurityException e){
            log.error("Responding \"GeneralSecurityException in Google API.\" in method getDirectoryService().");
            throw new BadRequestException("GeneralSecurityException in Google API.");
        }catch (IOException e){
            log.error("Responding \"Not connection with Google API.\" in method getDirectoryService().");
            throw new BadRequestException("Not connection with Google API.");
        }
    
        return service;
    }
    

    }

            Directory directory = directoryService.getDirectoryService(email);
            Users response = directory.users().list()
                    .setDomain("domain.com")
                    .setViewType("domain_public")
                    .setMaxResults(500)
                    .execute();