簡體   English   中英

OAuth 2.0訪問令牌和刷新令牌

[英]OAuth 2.0 Access Tokens and Refresh Tokens

我很難理解刷新和訪問令牌的正確用法。 我知道刷新令牌與授權有關,訪問令牌與身份驗證有關。我想更好地解釋我的用例,以便有人可以幫助我。 我在Google Merchant Center中設有多帳戶中心。 我想在我的代碼中集成最新的OAuth 2.0身份驗證機制。 我做了,可以成功驗證。 我使用Google Credential機制構建憑證對象,並在httprequest期間使用httprequestinitializer機制注入谷歌。 創建google憑據對象時,我發現當我執行googleCredential.getAccessToken()時沒有訪問令牌,但是當我執行googleCredential.refreshToken()然后googleCredential.getAccessToken()時,我獲得了accessToken 。 但是,我正在測試令牌是如何創建的,而且我沒有明確地在google請求中傳遞這些令牌。 我傳遞的只是帶有客戶端機密和其他私鑰的googleCredential對象。 我正在做的任務是通過cron腳本將子帳戶產品供稿上傳到谷歌。

我的問題是,

  1. 在這里傳遞googleCredential對象時,我是否需要處理刷新令牌? (假設腳本運行超過一天)
  2. 什么時候應該使用刷新令牌和訪問令牌,在上面的用例中,對我來說什么是正確的選擇? (雖然現在除了googleCredential對象之外我沒有明確傳遞任何內容)
  3. 訪問令牌和刷新令牌的有效時間是什么(與上述用例無關,只是要知道,有些人說刷新令牌有14天,有些人說無限期直到用戶撤銷訪問權限等)

如果有人澄清我並將我拉出來,我會很滿意的。 我知道這個平台主要是為了澄清代碼問題,但谷歌論壇也沒有幫助。 所以發帖在這里。

很抱歉非常啰嗦。

提前致謝。

所謂的OfflineCredentials需要刷新令牌 這些是可由應用程序使用的憑據,這些憑據不在瀏覽器中運行(例如,桌面應用程序或某些沒有UI的批處理),因此無法執行OAuth2流程。

請查看使用OAuth 2.0訪問Google API

  1. 如有必要,刷新訪問令牌。

訪問令牌的生命周期有限。 如果您的應用需要在單個訪問令牌的生命周期之后訪問Google API,則可以獲取刷新令牌。 刷新令牌允許您的應用程序獲取新的訪問令牌。

注意:在安全的長期存儲中保存刷新令牌,並且只要它們仍然有效,就繼續使用它們。 限制適用於每個客戶端 - 用戶組合以及所有客戶端中的每個用戶發布的刷新令牌的數量,並且這些限制是不同的。 如果您的應用程序請求足夠的刷新令牌超過其中一個限制,則較舊的刷新令牌將停止工作。

離線訪問的更多信息!

在Java中,它看起來像這樣:

import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.common.lib.auth.OfflineCredentials.ForApiBuilder;
import com.google.api.ads.common.lib.exception.OAuthException;
import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.client.auth.oauth2.Credential;

// ...

// Generate offline credentials
// With a previously created OAuth2 refresh token (see API examples)
ForApiBuilder forApiBuilder = new OfflineCredentials.Builder().forApi(Api.ADWORDS);
forApiBuilder.withClientSecrets(clientId, clientSecret);
forApiBuilder.withRefreshToken(refreshToken);

Credential credential = null;
try {
  credential = forApiBuilder.build().generateCredential();
} catch (OAuthException e) {
  throw new Exception("The given credential could not be refreshed: " + e.getMessage());
} catch (ValidationException e) {
  throw new Exception("Client ID, client secret or refresh token are not valid: " + e.getMessage());
}

// Build session
// ...

除了客戶端ID和客戶端密鑰之外,還需要將刷新令牌傳遞給憑據構建器。 借助有效的OfflineCredentials,您現在可以為特定的Google API構建新會話。

關於你的第三個問題 :請參閱以下問題的接受答案

此處是源代碼,其中顯示了如何通過命令行獲取Google AdWords的刷新令牌(請參閱范圍) 必須將客戶端ID和客戶端密鑰作為命令行參數傳遞。

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;

import com.google.api.ads.common.lib.auth.GoogleClientSecretsBuilder;
import com.google.api.ads.common.lib.auth.GoogleClientSecretsBuilder.Api;
import com.google.api.ads.common.lib.auth.GoogleClientSecretsBuilder.GoogleClientSecretsForApiBuilder;
import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
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.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.Lists;

// ...

  private static final String SCOPE = "https://adwords.google.com/api/adwords";

  // This callback URL will allow you to copy the token from the success screen
  private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";

  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Please provide client ID and secret as commandline arguments!");
      System.err.println("If you do not have a client ID or secret, please create one in the API console: https://code.google.com/apis/console#access");
      System.exit(1);
    }

    GoogleClientSecrets clientSecrets = null;
    try {
      Configuration configuration = new PropertiesConfiguration();
      configuration.setProperty("api.adwords.clientId", args[0]);
      configuration.setProperty("api.adwords.clientSecret", args[1]);

      GoogleClientSecretsForApiBuilder googleClientSecretsForApiBuilder = new GoogleClientSecretsBuilder().forApi(Api.ADWORDS);
      googleClientSecretsForApiBuilder.from(configuration);

      clientSecrets = googleClientSecretsForApiBuilder.build();
    } catch (ValidationException e) {
      System.err.println("Invalid client ID or secret!");
      System.exit(1);
    }

    // Get the OAuth2 credential
    Credential credential = getOAuth2Credential(clientSecrets);

    System.out.printf("Your refresh token is: %s\n", credential.getRefreshToken());
    }
  }

  private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets) throws Exception {
    /*
     * Set the access type to offline so that the token can be refreshed. By
     * default, the library will automatically refresh tokens when it can, but
     * this can be turned off by setting api.adwords.refreshOAuth2Token=false
     */
    GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), new JacksonFactory(), clientSecrets, Lists.newArrayList(SCOPE)).setAccessType("offline").build();

    String authorizeUrl = authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
    System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');

    // Wait for the authorization code
    System.out.println("Type the code you received here: ");
    String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // Authorize the OAuth2 token
    GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationFlow.newTokenRequest(authorizationCode);
    tokenRequest.setRedirectUri(CALLBACK_URL);
    GoogleTokenResponse tokenResponse = tokenRequest.execute();

    // Create the OAuth2 credential
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).setClientSecrets(clientSecrets).build();

    // Set authorized credentials
    credential.setFromTokenResponse(tokenResponse);

    return credential;
  }

該代碼最初來自Goolge AdWords API示例 我的版本不是從配置文件中讀取,因為我不想將客戶端ID和密碼存儲在某個資源文件中(我以后忘記刪除)。 這就是為什么值作為參數傳遞給程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM