401 Несанкционированный - Google Directory API с использованием Сервисной учетной записи

Я пытаюсь использовать Google Directory API для получения данных некоторых пользователей из домена. Также опуская Google Authentication, используя Service account ранее созданное и делегированное G Suite делегирование по домену в соответствии со ссылкой. Но во время потребления появляется ошибка .execute() оказание услуг:

-------------- RESPONSE --------------
HTTP/1.1 401 Unauthorized
Transfer-Encoding: chunked
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"
Server: ESF
X-Content-Type-Options: nosniff
Pragma: no-cache
Date: Tue, 13 Mar 2018 22:12:25 GMT
X-Frame-Options: SAMEORIGIN
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Encoding: gzip
Expires: Mon, 01 Jan 1990 00:00:00 GMT
X-XSS-Protection: 1; mode=block
Content-Type: application/json; charset=utf-8

2018-03-13 16:12:25.023:WARN:oejs.ServletHandler:qtp157627094-30: /google
com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized

Если я попробую этот API, выполняющий те же параметры, информация о данных будет работать хорошо. Итак, какие-либо детали, которые устанавливают плохо или есть какая-то идея?

public class GoogleDirectory {

    /** Email of the Service Account */
    private static final String SERVICE_ACCOUNT_EMAIL = "id@sanm-gcp-gae-qisdev.iam.gserviceaccount.com";

    /** Path to the Service Account's Private Key file */
    //public static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = dataP12.getPath();

    private static final List<String> SCOPES =
            Arrays.asList("https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.user");

    public GoogleDirectory() throws IOException {
    }

    /**
     * Build and returns a Directory service object authorized with the service accounts
     * that act on behalf of the given user.
     *
     * @param userEmail The email of the user. Needs permissions to access the Admin APIs.
     * @return Directory service object that is ready to make requests.
     */
    public static Directory getDirectoryService(String userEmail) throws GeneralSecurityException,
            IOException, URISyntaxException {
        File fileP12 = new ClassPathResource("file-638bb905b35d.p12").getFile();

        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(SCOPES)
                .setServiceAccountUser(userEmail)
                .setServiceAccountPrivateKeyFromP12File(fileP12)
                .build();
        Directory service = new Directory.Builder(httpTransport, jsonFactory, null)
                .setHttpRequestInitializer(credential).build();
        return service;
    }


    public void execute() throws IOException, GeneralSecurityException, URISyntaxException {
        // Build a new authorized API client service.
        Directory service = getDirectoryService("emailRegisteredInOAuthConsentScreen");

        // Print the first 10 users in the domain.
        Users result = service.users().list()
                .setDomain("domainexample.com")
                .setOrderBy("email")
                .setQuery("email@example.com")
                .setViewType("domain_public")
                .execute();
        List<User> users = result.getUsers();
        if (users == null || users.size() == 0) {
            System.out.println("No users found.");
        } else {
            System.out.println("Users:");
            for (User user : users) {
                System.out.println(user.getName().getFullName());
            }
        }
    }

}

Еще несколько подробностей о проекте:

  • Ява: 8
  • google-api-client: 1.23.0

1 ответ

Настройте в учетной записи Goggle права на использование учетной записи других приложений.
Войти в аккаунт.
Перейти к: Войти и меню безопасности
Далее: Приложения с доступом к аккаунту
Включите: Разрешить менее безопасные приложения: OFF -> ON

Другие вопросы по тегам