oauth - Google API OAuth2 - 从授权 token 获取刷新 token

标签 oauth google-api authorization google-oauth

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

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


我正在使用“其他”类型,因为应用程序只需要获取新的 access_token(使用 refresh_token),并且不会使用任何类型的用户同意。

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

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

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



使用以下请求(遵循 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)的正确方法是什么?

最佳答案

我想到了。

使用此请求:

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

关于oauth - Google API OAuth2 - 从授权 token 获取刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37775220/

相关文章:

Android:Twitter 和 OAuth 有人吗?

android - Google Api 和 android Oauth INVALID_AUDIENCE 错误

google-api - 是否可以将 google 身份验证(即服务帐户)用于自定义 API?

.net - 数据库文件无法保护时,如何在.NET中实现本地数据库?

javascript - HTML/JavaScript 应用程序的 LDAP 身份验证

node.js - 无效的 oauth2 token 请求

jquery - 在网站中显示自动授权的 Google Analytics 数据?

curl - Golang 单足/双足oauth 1.0a认证

google-maps - Google Maps API V3 错误 : RefererDeniedMapError

node.js - Node js请求的授权问题