Google App Engine App - аутентификация в API администратора Google - PullRequest
0 голосов
/ 13 декабря 2018

Я пытаюсь получить доступ к API-интерфейсу администратора Google для создания новых групп Google из приложения Java, которое работает на App Engine.Я использую следующие зависимости:

   <dependency>
     <groupId>com.google.api-client</groupId>
     <artifactId>google-api-client</artifactId>
     <version>1.25.0</version>
   </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client-appengine</artifactId>
      <version>1.25.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-admin-directory</artifactId>
        <version>directory_v1-rev105-1.25.0</version>
    </dependency>

Затем я пытаюсь создать группу Google, например:

final List<String> SCOPES = Collections.singletonList(DirectoryScopes.ADMIN_DIRECTORY_GROUP);

AppIdentityCredential appCredential = new AppIdentityCredential(SCOPES);

final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

Directory directory = new Directory.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential())
        .setApplicationName("Test")
        .build();

com.google.api.services.admin.directory.model.Group group = new Group();
group.setEmail("test@test.com");
group.setName("test_group");
group.setDescription("test_group_desc");

Group googleGroup = directory.groups().insert(group).execute();

Я получаю ошибку 403 и думаю,Мне нужно подтвердить подлинность по-другому.Я ознакомился со следующим руководством по использованию клиентской библиотеки Google API для Java в Google App Engine:

https://developers.google.com/api-client-library/java/google-api-java-client/app-engine

Здесь приводится ссылка на руководство по с использованием OAuth2.0 с потоком кода авторизации для приложений Google App Engine

В руководстве приведен следующий пример создания GoogleAuthorizationCodeFlow, однако нет объяснения, что такое getClientCredential() или что мне следуетвыполните в этой процедуре:

return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
    getClientCredential(), Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
    DATA_STORE_FACTORY).setAccessType("offline").build();

Этот раздел об использовании API идентификации App Engine выглядит многообещающе, однако нет объяснения того, как это можно использовать с клиентской библиотекой API администратора Google:

https://cloud.google.com/appengine/docs/standard/java/appidentity/#asserting_identity_to_google_apis

Что мне нужно сделать, чтобы аутентифицироваться в приложении, работающем в App Engine?

1 Ответ

0 голосов
/ 13 декабря 2018

Я рекомендую вам проверить образец быстрого запуска Java для Google Admin SDK Directory API.

Например, есть метод getCredentials, который вы можете использовать вместо getClientCredential

/**
 * Creates an authorized Credential object.
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = AdminSDKDirectoryQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
...