简体   繁体   中英

What is the alternative to the deprecated 'GoogleCredential'?

I'd been employing the following Java method to set a bucket notification in 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);
  }
}

It's been working fine so far, but lately, I'm getting a complaint regarding the deprecation of GoogleCredential class, and tried doing some research with a hope to find a possible replacement, but couldn't find anything. Can anyone help me point in the right direction?

After a while of looking around, I managed to fix it, using GoogleCredentials and HttpRequestInitializer . The code changes are as follows.

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

becomes

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

You can find an alternative solution as being posted on the Google APIs Github repository commits .

Please use Google Auth Library for Java for handling Application Default Credentials and other non-OAuth2 based authentication.

Explicit Credential Loading sample code:

To get Credentials from a Service Account JSON key use GoogleCredentials.fromStream(InputStream) or GoogleCredentials.fromStream(InputStream, HttpTransportFactory). Note that the credentials must be refreshed before the access token is available.

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

I had to solve similar task when using Google Admin SDK API and
com.google.api.services.admin.directory.Directory was needed.

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

Use google-auth-library-oauth2-http library

Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM