【问题标题】:Authorization to Google Client对 Google 客户端的授权
【发布时间】:2014-01-08 04:07:02
【问题描述】:

我正在编写一个用于创建 BigQuery 和 Google Cloud Storage 授权的类。

过去我使用过CredentialStore,它已被弃用。我正在尝试使用DataStoreFactory,但我发现它只允许我使用StoredCredential,而我需要Credential

我知道可以从Credential 转换为StoredCredential,但我不确定如何将它们转换为相反的方向(StoredCredentialCredential)。例如,我正在创建这样的连接:

Storage.Builder(HttpTransport transport,
    JsonFactory jsonFactory,
    HttpRequestInitializer httpRequestInitializer);


谁能指出我如何实现这一目标的方向?

谢谢!

【问题讨论】:

    标签: java client google-bigquery google-cloud-storage


    【解决方案1】:

    在大多数情况下,无论您在何处使用Credential,都可以使用StoredCredential。您只能使用Credential 的一点,即在OAuth 回调期间检索访问令牌。从那里可以将Credential 转换为StoreCredential 并存储到DataStore 中。之后存储和检索都可以使用StoredCredential

    但是有些地方StoredCredential 不能用。我刚刚遇到一个尝试创建 Google Drive API 服务包装器的人。

    有一种方法可以使用 GoogleCredential 对象解决此问题,它可以根据以下答案从 StoredCredential 创建:
    Stored Credential from Google API to be reused using Java

    import com.google.api.client.auth.oauth2.StoredCredential;
    
    public static GoogleCredential createGoogleCredential(StoredCredential storedCredential) {
        GoogleCredential googleCredential = new GoogleCredential.Builder()
            .setTransport(new NetHttpTransport())
            .setJsonFactory(new JacksonFactory())
            .setClientSecrets("client_id", "client_secret")
            .setAccessToken(storedCredential.getAccessToken())
            .build();
    
        return googleCredential;
    }
    

    【讨论】:

    • 你的代码中哪个是哪个?什么是凭证对象?我认为 storedCredential 是您自己的数据库中的一个。
    • 是的。我已经编辑了答案以明确说明。
    【解决方案2】:

    我正在使用 google-oauth-client-1.22.0.jar。

    我有一个带有静态 Service Account 凭据的 Java 服务器,它通过 Google Cloud 进行身份验证。

    这是我使用的显着代码。

    这里的关键是添加一个CredentialRefreshListener,当您成功进行身份验证时,Google OAuth 客户端库将调用并为您提供一个您可以序列化和存储的StoredCredential 对象。您可以通过编写或实例化DataStore 接口的实现将其存储和检索到您选择的位置。您的DataStore 实现是使用DataStoreFactory 实现构建的。

    在构建我的GoogleCredential 之后,我可以从我的DataStore 中读取最后一个访问令牌、刷新令牌和到期日期。 如果访问令牌不会过期,那么 Google 客户端 API 将使用它来登录。 当它即将到期时,或者这是第一次调用此代码时,Google Client API 将调用刷新侦听器并存储第一个访问令牌、刷新令牌和到期日期。

    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.
      }
    

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 2014-11-18
      • 2018-07-11
      • 2017-02-22
      • 2023-03-24
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多