gpt4 book ai didi

google-oauth - OAuth 2.0 访问 token 和刷新 token

转载 作者:行者123 更新时间:2023-12-04 17:47:37 26 4
gpt4 key购买 nike

我很难理解刷新和访问 token 的正确用法。我知道刷新 token 与授权有关,访问 token 与身份验证有关。我想更好地解释我的用例,以便有人可以在这里帮助我。我在 Google Merchant Center 中有一个多帐户中心。我想在我的代码中集成最新的 OAuth 2.0 身份验证机制。我做到了并且可以成功进行身份验证。我使用 Google Credential 机制来构建凭据对象,并在向 google 发送 httprequest 期间使用 httprequestinitializer 机制注入(inject)。创建 google credential 对象时,我看到执行 googleCredential.getAccessToken() 时没有访问 token ,但是当我执行 googleCredential.refreshToken() 和 googleCredential.getAccessToken() 时,我得到一个 accessToken .但是,我正在测试如何创建 token ,并且我没有在请求中明确地将这些 token 传递给谷歌。我传递的只是带有客户端 secret 和其他私钥的 googleCredential 对象。我正在做的任务只是通过 cron 脚本将子帐户产品提要上传到谷歌。

我的问题是,

  • 在此处传递 googleCredential 对象时,我是否必须在此处处理刷新 token ? (假设脚本运行超过一天)
  • 什么时候应该使用刷新 token 和访问 token ,在上述用例中对我来说什么是正确的选择? (虽然现在我没有明确传递任何东西,除了 googleCredential 对象)
  • 访问 token 和刷新 token 的有效期是多少(与上述用例无关,只是要知道,有人说刷新 token 为 14 天,有人说无限期直到用户撤销访问权限等)

  • 如果有人澄清我并把我拉出来,我会很高兴。我知道这个平台主要是为了澄清代码上的问题,但我的谷歌论坛也没有帮助。所以在这里发帖。

    很抱歉非常冗长。

    提前致谢。

    最佳答案

    一个 刷新 token 所谓的 是必需的离线凭证 .这些凭据可以由不在浏览器中运行的应用程序使用(例如桌面应用程序或一些没有 UI 的批处理),因此无法执行 OAuth2 流程。
    请查看Using OAuth 2.0 to Access Google APIs

    1. Refresh the access token, if necessary.

    Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

    Note: Save refresh tokens in secure long-term storage and continue to use them as long as they remain valid. Limits apply to the number of refresh tokens that are issued per client-user combination, and per user across all clients, and these limits are different. If your application requests enough refresh tokens to go over one of the limits, older refresh tokens stop working.


    更多信息到 Offline Access !
    在 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 和客户端密码之外,还需要将刷新 token 传递给凭证生成器。使用有效的 OfflineCredentials,您现在可以为特定的 Google API 构建新 session 。
    关于你的第三个问题 :请参阅以下 question 的已接受答案
    这里是源代码,它显示了如何获取 的刷新 token 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 example .我的版本不是从配置文件中读取的,因为我不想将客户端 ID 和 secret 存储在某个资源文件中(稍后我忘记删除了)。这就是为什么将这些值作为参数传递给程序的原因。

    关于google-oauth - OAuth 2.0 访问 token 和刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272849/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com