0

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

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

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 文档中,我发现我可以通过浏览器重定向获取刷新令牌并将其保存在数据库中。(换句话说,我可以使用离线访问)。

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

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

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,而不是从谷歌 API 控制台安装应用程序吗?我不能在已安装的应用程序中更改重定向 URI 吗?我很困惑,我不知道,我应该使用哪个。

4

1 回答 1

0

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);
    }
  }

有关更多信息,请参阅实现服务器端授权令牌部分。

获得刷新令牌后,您必须保存它。有关更多信息,请参见该示例

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

于 2013-08-22T11:34:17.107 回答