【问题标题】:can't get access token using refresh token无法使用刷新令牌获取访问令牌
【发布时间】:2013-08-23 23:36:39
【问题描述】:

我在 java 上编写了桌面应用程序,它可以访问 Google 驱动器。 (它只是上传和下载文件)。

目前访问类型为在线。当我需要访问驱动器的文件/文件夹时,我 将浏览器重定向到 Google 网址并获取访问代码:

String code = "code that was returned from brouser"
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

一切正常!但我只需要第一次进行重定向。

当我谷歌时,在Google Drive API documentation 中,我发现我可以通过浏览器重定向获取刷新令牌并将其保存在数据库中。 (换句话说,我可以使用离线访问)。

每次我需要从谷歌驱动器读取数据时,我都会使用刷新令牌获取访问令牌,而无需重定向。不是吗?

所以我得到这样的刷新令牌:

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=695230079990.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/drive&response_type=code&redirect_uri=https://localhost

问题 1
我从浏览器重定向中获取代码。它是刷新令牌,不是吗? 现在,我需要使用该刷新令牌获取访问令牌。

 $.ajax({
      type: "POST",
      url: 'https://accounts.google.com/o/oauth2/token',
      data: {
        client_id: "695230079990.apps.googleusercontent.com",
        client_secret: 'OWasYmp7YQ...4GJaPjP902R',
        refresh_toke: '4/hBr......................xwJCgQI',
        grant_type: 'refresh_token'
      },
      success: function(response) { 
        alert(response);
      }

    });

但我有错误 400

问题 2) 当我尝试更改重定向 url 时出现错误:*

redirect_uri 的参数值无效:不允许非公共域:https://sampl.ecom

那么,我必须创建 Web 应用程序客户端 ID,而不是从 google API 控制台安装应用程序吗?我不能在已安装的应用程序中更改重定向 URI 吗?我很困惑,我不知道,我应该使用哪个。

【问题讨论】:

    标签: oauth oauth-2.0 google-drive-api google-drive-realtime-api


    【解决方案1】:

    1) 当您尝试离线访问时,您会获得授权码,该码可用于兑换访问令牌和刷新令牌。

    举个例子:

    https://accounts.google.com/o/oauth2/auth?access_type=offline
    &approval_prompt=auto
    &client_id=[your id]
    &redirect_uri=[url]
    &response_type=code
    &scope=[access scopes]
    &state=/profile
    

    在你获得授权码后,你会得到刷新令牌。

     static Credential exchangeCode(String authorizationCode)
          throws CodeExchangeException {
        try {
          GoogleAuthorizationCodeFlow flow = getFlow();
          GoogleTokenResponse response =
              flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
          return flow.createAndStoreCredential(response, null);
        } catch (IOException e) {
          System.err.println("An error occurred: " + e);
          throw new CodeExchangeException(null);
        }
      }
    

    有关更多信息,请参阅Implementing Server-side Authorization 令牌部分。

    在你得到 refresh token 后,你必须保存它。有关更多信息,请参阅sample

    2) 如果您没有安装应用程序,您应该创建 Web 应用程序来更改重定向 URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-19
      • 2020-02-26
      • 2022-01-23
      • 2019-10-26
      • 2021-12-17
      • 2016-09-28
      • 2015-11-26
      相关资源
      最近更新 更多