【问题标题】:Google API OAuth2 - Get refresh token from Authorization tokenGoogle API OAuth2 - 从授权令牌获取刷新令牌
【发布时间】:2016-10-13 00:20:30
【问题描述】:

按照Using OAuth 2.0 for Installed Applications 中描述的步骤,我已经能够为我的应用程序获取授权码。

我已在 Google Developers Console 中将我的应用程序注册为 OAuth 2.0 客户端 ID:

我使用的是“Other”类型,因为应用程序只需要获取一个新的 access_token(使用 refresh_token),不会使用任何类型的用户同意。

安全性无关紧要,因为它将是一个私有应用程序。

应用程序需要能够读取和写入电子表格,并运行链接到电子表格的 Google Apps 脚本。

根据Google's OAuth 2.0 Playground,这在“https://www.googleapis.com/auth/spreadsheets”范围内都是可能的:

我已经能够使用以下请求(遵循this 步骤)获得授权代码:

https://accounts.google.com/o/oauth2/v2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets&
redirect_uri=urn:ietf:wg:oauth:2.0:oob&
response_type=code&
client_id=#####.apps.googleusercontent.com

将此 URL 粘贴到我的浏览器中,它会将我重定向到此页面:

这样我获得了一个授权码,理论上可以换成一个 refresh_token 和一个 access_token。

我尝试模仿 Google 的 OAuth 2.0 Playground 在将授权码交换为 refresh_token 和 access_token 时所做的请求:

它向以下 URL 发送 POST 请求:

https://www.googleapis.com/oauth2/v3/token?
  code={auth_code}&
  redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&
  client_id=#####.apps.googleusercontent.com&
  client_secret=#####&
  scope=&
  grant_type=authorization_code

当我尝试执行此请求时,我收到 ERROR 400 和以下响应:

 {"error": "invalid_request", "error_description": "Invalid parameter value for redirect_uri: Missing scheme: {redirect_uri}}

它会为 redirect_uri 引发有关“缺少方案”的错误。在我看来这并不奇怪,因为我的应用程序类型是“其他”,而您不能使用该类型授权重定向 URI

我已经尝试了OAuth2ForDevices(这正是我想要的),但我不能将它用于 Google 的电子表格。

使用授权码(通过客户端 ID 类型“其他”(可用于 Google 电子表格)获得)获取 refresh_token(和 access_token)的正确方法是什么? p>

【问题讨论】:

    标签: oauth google-api authorization google-oauth


    【解决方案1】:

    使用与调用相同的redirect_uri:

    https://accounts.google.com/o/oauth2/v2/auth

    Google 不会对该 uri 发出任何进一步的请求,但我认为它会将其用于匹配目的,作为一些小的附加安全性。

    【讨论】:

      【解决方案2】:

      我想通了。

      使用这个请求:

      https://accounts.google.com/o/oauth2/v2/auth?
        scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets&
        redirect_uri=urn:ietf:wg:oauth:2.0:oob&
        response_type=code&
        client_id=#####.apps.googleusercontent.com
      

      这会返回一个授权码。 然后,发出以下 POST 请求:

      POST /oauth2/v4/token HTTP/1.1
      Host: www.googleapis.com
      Content-Type: application/x-www-form-urlencoded
      
      code={auth_code}&
      client_id=######.apps.googleusercontent.com&
      client_secret=#####&
      redirect_uri=urn:ietf:wg:oauth:2.0:oob&
      grant_type=authorization_code
      

      如果你不使用“urn:ietf:wg:oauth:2.0:oob”作为你的redirect_uri,它就不起作用。这在OAuth2InstalledApp Guide 中没有说明(它使用“https://oauth2-login-demo.appspot.com/code”作为redirect_uri 的示例,这让我很困惑)。

      简答:使用“urn:ietf:wg:oauth:2.0:oob”作为redirect_uri

      【讨论】:

        猜你喜欢
        • 2018-06-23
        • 1970-01-01
        • 2016-08-03
        • 2015-02-24
        • 1970-01-01
        • 2012-06-29
        • 2018-02-27
        • 2019-06-18
        • 2021-08-19
        相关资源
        最近更新 更多