Google customer authorization

I am writing a class to create authorization for Bigquery and Google Cloud Storage. I used to use CredentialStore, which is deprecated. I am trying to use a DataStoreFactory, but I found that it allows me to use only the StoredCredential, while I need Credential. I know that you can convert from Credential to StoredCredential, but I'm not sure how to convert them in the opposite direction (StoredCredential for Credential). I create my connection using, for example, Storage.Builder (HttpTransport transport, JsonFactory jsonFactory, HttpRequestInitializer httpRequestInitializer)

Can someone tell me how to do this? Thank!

+3
source share
2 answers

In most cases, wherever you use Credential, you can use StoredCredential. There is only one point that you will use with Credential, which retrieves the access token during the OAuth callback. From there, credentials can be converted to StoreCredential and saved to the DataStore. After this storage and search, everything works with the StoredCredential.

But there are places where the StoredCredential cannot be used. I just came across an attempt to create a wrapper for the Google Drive API service.

There is a way around this using the GoogleCredential object, it can be created from StoredCredential according to this answer: Stored credentials from google api for reusing java

import com.google.api.client.auth.oauth2.StoredCredential;

public static GoogleCredential createGoogleCredential(StoredCredential storedCredential)
{
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential googleCredential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets("client_id", "client_secret").build();
    googleCredential.setAccessToken(storedCredential.getAccessToken());
    return googleCredential;
}
+1

google-oauth-client-1.22.0.jar.

Java , Google Cloud.

, .

CredentialRefreshListener, Google OAuth StoredCredential, . , DataStore. DataStore DataStoreFactory.

GoogleCredential, , DataStore. , API- Google . , , , API- Google , .

import com.google.api.client.auth.oauth2.DataStoreCredentialRefreshListener;
import com.google.api.client.auth.oauth2.StoredCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.IOUtils;
import com.google.api.client.util.store.AbstractDataStore;
import com.google.api.client.util.store.AbstractDataStoreFactory;
import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.StorageObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.Base64;

public class StackOverflow {

  public static void main(final String... args) throws Exception {
    final String clientEmail = "todd.snider@aimless.com";
    final HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory jsonFactory = new JacksonFactory();
    // This implementation generates an that stores and retrieves StoredCredential objects
    final DataStoreFactory dataStoreFactory = new AbstractDataStoreFactory() {
      @Override
      protected <V extends Serializable> DataStore<V> createDataStore(final String id) {
        return new MyDataStore<>(this, id);
      }
    };
    // construct a GoogleCredential object to access Google Cloud
    final GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(clientEmail)
        .setServiceAccountScopes(StorageScopes.all())
        .setServiceAccountPrivateKey(readEncryptedPemFile())
        .setServiceAccountPrivateKeyId("___static_get_this_from_google_console___")
        .addRefreshListener(new DataStoreCredentialRefreshListener(clientEmail, dataStoreFactory))
        .build();
    // See I have an access token, refresh token and expiration date stored in my DataStore.
    // If so, set them on the GoogleCredential
    final StoredCredential storedCredential = StoredCredential.getDefaultDataStore(dataStoreFactory).get(clientEmail);
    if (storedCredential != null) {
      credential.setAccessToken(storedCredential.getAccessToken());
      credential.setRefreshToken(storedCredential.getRefreshToken());
      credential.setExpirationTimeMilliseconds(storedCredential.getExpirationTimeMilliseconds());
    }
    // Now I can use Google Cloud
    final Storage storage = new Storage.Builder(credential.getTransport(), credential.getJsonFactory(), credential).setApplicationName("Aimless").build();
    storage.objects().insert("soem bucket", new StorageObject());
  }

  private static class MyDataStore<V extends Serializable> extends AbstractDataStore<V> {

    MyDataStore(DataStoreFactory dataStoreFactory1, String id1) {
      super(dataStoreFactory1, id1);
    }

    @Override
    public DataStore<V> set(String key, V value) throws IOException {
      final String encoded = Base64.getEncoder().encodeToString(IOUtils.serialize(value));
      db.save(key, encoded);
      return this;
    }

    @Override
    public V get(String key) throws IOException {
      final String encoded = db.get(key);
      if (encoded == null) {
        return null;
      }
      return IOUtils.deserialize(Base64.getDecoder().decode(encoded));
    }

    // etc.
  }
0

Source: https://habr.com/ru/post/1543909/


All Articles