【问题标题】:What is the alternative to the deprecated 'GoogleCredential'?已弃用的“GoogleCredential”的替代方法是什么?
【发布时间】:2019-09-17 10:45:22
【问题描述】:

我一直在使用以下 Java 方法在 GCS 中设置存储桶通知。

private void setBucketNotification(String bucketName, String topicId) {

List<String> eventType = new ArrayList<>();
eventType.add("OBJECT_FINALIZE");

try {
  Notification notification = new Notification();
  notification.setTopic(topicId);
  notification.setEventTypes(eventType);
  notification.setPayloadFormat("JSON_API_V1");

  final GoogleCredential googleCredential = GoogleCredential
      .fromStream(Objects.requireNonNull(classloader.getResourceAsStream("Key.json")))
      .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));  

  final com.google.api.services.storage.Storage myStorage = new com.google.api.services.storage.Storage.Builder(
      new NetHttpTransport(), new JacksonFactory(), googleCredential).build();

  Notification v = myStorage.notifications().insert(bucketName, notification).execute();

} catch (IOException e) {
  log.error("Caught an IOException {}",e);
  }
}

到目前为止它运行良好,但最近,我收到了关于 GoogleCredential 类的弃用的投诉,并尝试进行一些研究以希望找到可能的替代品,但找不到任何东西。谁能帮我指出正确的方向?

【问题讨论】:

  • 您在哪里看到 GoogleCredential 已被弃用?
  • 也许您需要更改您正在使用的库? google-auth-library-java 或 com.google.apis:google-api-services-oauth2:v1-rev155-1.25.0
  • @JohnHanley 初始化的地方。
  • 请在您的问题中包含确切的信息。我的构建没有显示已弃用的消息。您使用的是哪个 Java 版本和 JDK?
  • @JohnHanley 它只是说'com.google.api.client.googleapis.auth.oauth2.GoogleCredential 已弃用'。我不知道除此之外我能有多准确和清晰。我正在使用 java 版本“1.8.0_212”。

标签: java google-cloud-platform google-cloud-storage


【解决方案1】:

环顾四周后,我设法使用GoogleCredentialsHttpRequestInitializer 修复了它。代码改动如下。

final GoogleCredential googleCredential = GoogleCredential
  .fromStream(Objects.requireNonNull(classloader.getResourceAsStream("Key.json")))
  .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));

final com.google.api.services.storage.Storage myStorage = new com.google.api.services.storage.Storage.Builder(
      new NetHttpTransport(), new JacksonFactory(), googleCredential).build();

变成

final GoogleCredentials googleCredentials = serviceAccountCredentials
                    .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));
            HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(googleCredentials);        

final com.google.api.services.storage.Storage myStorage = new com.google.api.services.storage.Storage.Builder(
                new NetHttpTransport(), new JacksonFactory(), requestInitializer).build();

【讨论】:

  • 谢谢@Roshan!对我来说棘手的部分是如何从GoogleCredentials 获取HttpRequestInitializer;谷歌搜索把我带到了这里:)
  • 如何使用 p12 私钥文件获取服务帐户凭据?
  • @insa_c 为什么不用json 文件和ServiceAccountCredentials,像这样:ServiceAccountCredentials.fromStream(Objects.requireNonNull(classloader.getResourceAsStream("Key.json"))) .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));
  • HttpCredentialsAdapter 是我所需要的,谢谢!
【解决方案2】:

您可以在 Google APIs Github repository commits 上找到替代解决方案。

请使用 Google Auth Library for Java 来处理应用程序默认凭据和其他基于非 OAuth2 的身份验证。

显式凭据加载示例代码:

要从服务帐户 JSON 密钥获取凭据,请使用 GoogleCredentials.fromStream(InputStream) 或 GoogleCredentials.fromStream(InputStream, HttpTransportFactory)。请注意,必须在访问令牌可用之前刷新凭据。

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/path/to/credentials.json"));
credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();
// OR
AccessToken token = credentials.refreshAccessToken();

【讨论】:

  • 这是一个仅链接的答案 - 即使它提供了正确的信息,我强烈希望您可以添加一个有关如何使用 api (-1) 的示例
  • 嘿@MartinFrank。你是完全正确的。超链接可以被修改或破坏。添加一些示例代码或文本以进一步解释始终是最佳实践。自从我发布这个答案以来已经有一段时间了。那是在我刚开始使用 Stackoverflow 的时候,我并没有意识到这些事情。请多多包涵。感谢您指出。
  • 我现在会提供一个答案 - 但如果你改变你的答案(至少稍微),我肯定会删除我的 -1
  • @MartinFrank 完美!我相信我编辑的答案现在提供了凭据加载的基本示例以及不推荐使用的 GoogleCredential 类如何更改为 GoogleCredentials 谢谢。
  • 虽然这个答案显示了一些使用GoogleCredentials 的方法,但它确实显示了如何从中获取HttpRequestInitializer,这是使用它所必需的它作为问题代码中已弃用的GoogleCredential 的替代品(@Roshan 的回答中对此进行了解释)。
【解决方案3】:

在使用 Google Admin SDK API 时,我必须解决类似的任务,并且
需要 com.google.api.services.admin.directory.Directory。

    final ServiceAccountCredentials serviceAccountCredentials = ServiceAccountCredentials.fromPkcs8(
            clientId,
            clientEmail,
            serviceAccountPkcs8Key,
            serviceAccountPkcs8Id,
            Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY));
    final GoogleCredentials delegatedCredentials = serviceAccountCredentials.createDelegated(delegatedUserEmail);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(delegatedCredentials);

    Directory directory = new Directory.Builder(httpTransport, JSON_FACTORY, requestInitializer)
            .setApplicationName(applicationName)
            .build();

【讨论】:

    【解决方案4】:

    使用google-auth-library-oauth2-http

    代码:

    ServiceAccountCredentials getServiceAccountCredentials(String privateKeyJson) 
    throws IOException {
       try (InputStream stream = new ByteArrayInputStream(privateKeyJson.getBytes())) {
          return ServiceAccountCredentials.fromStream(stream);
       }
    }
    
    ServiceAccountCredentials serviceAccountCredentials = getServiceAccountCredentials(privateKeyJson);
    String privateKeyId = serviceAccountCredentials.getPrivateKeyId();
    RSAPrivateKey key = (RSAPrivateKey)  serviceAccountCredentials.getPrivateKey();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2021-12-13
      相关资源
      最近更新 更多