当前位置: 首页 > 知识库问答 >
问题:

java api中的BigQuery实例在使用具有刷新令牌的凭据构建后是否会自动刷新其Oauth 2.0授权?

傅越
2023-03-14

美好的一天,

我最近正在通过java api测试Oauth2.0安装的bigquery应用程序身份验证。我使用这个命令行示例作为源代码,因为我想让用户eaiser可以访问它(要求他们复制代码会很难看)

如果我在GoogleAuthorizationCodeflow中使用SetAccessType(Offline),它会自动为我刷新访问令牌。

在相关的我想问,如果我授权一个com.google.api.services.bigquery.Bigquery实例与com.google.api.services.bigquery.Bigquery. Builder. Builder(HttpTransfer传输,JsonFactory jsonFactory,HttpRequest estLaunalizer httpRequest estLaunalizer)使用具有刷新令牌的凭据,我必须重新授权它还是它会更新自己内部的凭据?

如果在一小时后(令牌过期时间)它没有给我一个到bigquery的有效连接,那么哪种方法是重新授权客户端的最佳方法?

我应该使用凭据吗?刷新令牌(),然后用新的访问令牌构建另一个大查询实例,还是有更好的方法?

(我可能还想更改凭据Refreshlistener,但问题是,如果我使用GoogleAuthorizationCodeflow.createAndStoreCredential(response,Clientid)实例化凭据,之后我将无法获取Refreshlistener。如何获取它,以便我可以使用该类自动重新授权我的Bigquery客户端

codelow将刷新的访问令牌存储在哪里(如果它自动刷新)?如果我这样声明:

new GoogleAuthorizationCodeFlow.Builder(
              transport, jsonFactory, clientSecrets, scopes).setAccessType("offline")
              .setApprovalPrompt("auto").setCredentialStore(new MemoryCredentialStore()).build();

它是否会将刷新的访问令牌始终存储在MemoryCredentialStore中?所以如果我使用。getCredentialStore()。加载(用户ID、凭据)它将从memorystore加载刷新的访问令牌?

当访问令牌有效时,是否有办法增加或减少时间?因为出于测试目的,我真的很想这样做。

p. s:我也在研究google-api-java-Client和google-oauth-java-Client的源代码,但我仍然找不到解决方案。

最重要的是,我正在研究:代码处的类凭据:public void intercept(HttpRequest请求)抛出IOException{lock.lock();…但我无法确定何时调用此方法,最终我在问题中迷失了方向。

期待你的回答:阿提拉

共有1个答案

寇夜洛
2023-03-14

这里有很多问题。您将希望使用GoogleCredential类从现有的刷新令牌中获得一个新的访问令牌,您需要存储该令牌(使用您想要的任何方法,例如MemoryCredentialStore)。

访问令牌仅持续一小时,无法更改。

以下是使用已安装流的示例:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.Bigquery.Datasets;
import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.model.DatasetList;


class BigQueryInstalledAuthDemo {

  // Change this to your current project ID
  private static final String PROJECT_NUMBER = "XXXXXXXXXX";

  // Load Client ID/secret from client_secrets.json file.
  private static final String CLIENTSECRETS_LOCATION = "client_secrets.json";
  static GoogleClientSecrets clientSecrets = loadClientSecrets();

  private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

  // Objects for handling HTTP transport and JSON formatting of API calls
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static GoogleAuthorizationCodeFlow flow = null;

  // BigQuery Client
  static Bigquery bigquery;


  public static void main(String[] args) throws IOException {

    // Attempt to Load existing Refresh Token
    String storedRefreshToken = loadRefreshToken();

    // Check to see if the an existing refresh token was loaded.
    // If so, create a credential and call refreshToken() to get a new
    // access token.
    if (storedRefreshToken != null) {

      // Request a new Access token using the refresh token.
      GoogleCredential credential = createCredentialWithRefreshToken(
          HTTP_TRANSPORT, JSON_FACTORY, new TokenResponse().setRefreshToken(storedRefreshToken));
      credential.refreshToken();

      bigquery = buildService(credential);

    // If there is no refresh token (or token.properties file), start the OAuth
    // authorization flow.
    } else {
      String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(
          clientSecrets,
          REDIRECT_URI,
          Collections.singleton(BigqueryScopes.BIGQUERY)).setState("").build();

      System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl);

      System.out.println("... and type the code you received here: ");
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String authorizationCode = in.readLine();

      // Exchange the auth code for an access token and refesh token
      Credential credential = exchangeCode(authorizationCode);

      // Store the refresh token for future use.
      storeRefreshToken(credential.getRefreshToken());

      bigquery = buildService(credential);
    }

    // Make API calls using your client.
    listDatasets(bigquery, PROJECT_NUMBER);

  }


  /**
   *  Builds an authorized BigQuery API client.
   */
  private static Bigquery buildService(Credential credential) {
    return new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
  }


  /**
   * Build an authorization flow and store it as a static class attribute.
   */
  static GoogleAuthorizationCodeFlow getFlow() {
    if (flow == null) {
      flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
          JSON_FACTORY,
          clientSecrets,
          Collections.singleton(BigqueryScopes.BIGQUERY))
      .setAccessType("offline").setApprovalPrompt("force").build();
    }
    return flow;
  }


  /**
   * Exchange the authorization code for OAuth 2.0 credentials.
   */
  static Credential exchangeCode(String authorizationCode) throws IOException  {
    GoogleAuthorizationCodeFlow flow = getFlow();
    GoogleTokenResponse response =
        flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
    return flow.createAndStoreCredential(response, null);
  }


  /**
   * No need to go through OAuth dance, get an access token using the
   * existing refresh token.
   */
  public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
      JsonFactory jsonFactory, TokenResponse tokenResponse) {
    return new GoogleCredential.Builder().setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets(clientSecrets)
        .build()
        .setFromTokenResponse(tokenResponse);
  }


  /**
   *  Helper to load client ID/Secret from file.
   */
  private static GoogleClientSecrets loadClientSecrets() {
    try {
      GoogleClientSecrets clientSecrets =
          GoogleClientSecrets.load(new JacksonFactory(),
              BigQueryInstalledAuthDemo.class.getResourceAsStream(CLIENTSECRETS_LOCATION));
      return clientSecrets;
    } catch (Exception e)  {
      System.out.println("Could not load clientsecrets.json");
      e.printStackTrace();
    }
    return clientSecrets;
  }


  /**
   *  Helper to store a new refresh token in token.properties file.
   */
  private static void storeRefreshToken(String refresh_token) {
    Properties properties = new Properties();
    properties.setProperty("refreshtoken", refresh_token);
    System.out.println(properties.get("refreshtoken"));
    try {
      properties.store(new FileOutputStream("token.properties"), null);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  /**
   *  Helper to load refresh token from the token.properties file.
   */
  private static String loadRefreshToken(){
    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream("token.properties"));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return (String) properties.get("refreshtoken");
  }


  /**
   *
   * List available Datasets.
   */
  public static void listDatasets(Bigquery bigquery, String projectId)
      throws IOException {
    Datasets.List datasetRequest = bigquery.datasets().list(projectId);
    DatasetList datasetList = datasetRequest.execute();
    if (datasetList.getDatasets() != null) {
      List<DatasetList.Datasets> datasets = datasetList.getDatasets();
      System.out.println("Available datasets\n----------------");
      for (com.google.api.services.bigquery.model.DatasetList.Datasets dataset : datasets) {
        System.out.format("%s\n", dataset.getDatasetReference().getDatasetId());
      }
    }
  }

}
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.Bigquery.Datasets;
import com.google.api.services.bigquery.model.DatasetList;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class JavaCommandLineServiceAccounts {

  private static final String SCOPE = "https://www.googleapis.com/auth/bigquery";
  private static final HttpTransport TRANSPORT = new NetHttpTransport();
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static Bigquery bigquery;

  public static void main(String[] args) throws IOException, GeneralSecurityException {
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId("XXXXXXX@developer.gserviceaccount.com")
        .setServiceAccountScopes(SCOPE)
        .setServiceAccountPrivateKeyFromP12File(new File("my_file.p12"))
        .build();

    bigquery = new Bigquery.Builder(TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName("BigQuery-Service-Accounts/0.1")
        .setHttpRequestInitializer(credential).build();

    Datasets.List datasetRequest = bigquery.datasets().list("publicdata");
    DatasetList datasetList = datasetRequest.execute();
    System.out.format("%s\n", datasetList.toPrettyString());
  }

}
 类似资料:
  • 我在自己的Web API上使用Oauth2,在Web应用程序上使用ASP.NET C#来使用该API。在我的web应用程序上,我正在进行HttpWebRequests。当我的访问令牌过期时,我调用一个方法“refreshToken”,该方法发出请求以获取新的访问令牌。这工作很好,没有问题...除了我得到的响应包含一个新的刷新令牌???我在等新的访问令牌。我甚至认为在没有再次传递凭据的情况下这是不可

  • 问题内容: 我正在使用Firebase电子邮件/密码身份验证。用户成功登录后,我将通过以下方式查询访问令牌: 根据Firebase文档,访问令牌会在1小时后过期。为了处理在我的应用程序中始终具有当前访问令牌的情况,我在寻找解决方案,并且在firebase文档中发现我必须注册Firebase.IdTokenListener来侦听 onIdTokenChanged事件 我的问题是 : onIdToke

  • onIdTokenChanged事件 我的问题是: onIdTokenChanged事件 IDTokenListener 被触发。但这不是我要找的。

  • 由于访问令牌的寿命很短,所以我使用刷新令牌来获得一个新的访问令牌。成功的令牌响应将包括以下内容(来自microsoft api doc的示例): 我已经读到refresh_token的生命期是有效的,直到撤销或90天不活动。既然我得到了一个新的刷新令牌,我需要用这个新的刷新令牌替换旧的刷新令牌吗?如果我做了,如何删除旧的刷新令牌? 谢了!

  • 我使用WSO2 API manager 1.10.0,WSO2 Identity Server 5.1.0配置为密钥管理器,MySQL Community Server 5.6用于数据库。当我尝试刷新通过授权代码授权类型获得的令牌(refresh_token授权类型)时,我收到400错误请求错误(invalid_grant -提供的授权授权无效),并且我无法获得新令牌。然后,我尝试使用client

  • 在我的Java/Ionic2应用程序中,我通过REST服务请求使用刷新令牌对Google Drive进行身份验证,然后使用access_type=offline,如下所述:https://developers.Google.com/identity/protocols/oauth2webserver#refresh。 服务器响应200 OK,所以它给我一个刷新和一个访问令牌,只是在我第一次请求访问