什么是不推荐使用的“GoogleCredential”的替代方案?

我一直在使用以下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


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

答案 2

您可以找到一个替代解决方案,发布在Google API Github存储库提交中

请使用适用于 Java 的 Google 身份验证库来处理应用程序默认凭据和其他非基于 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();

推荐