2016-06-12 275 views
3

按照Using OAuth 2.0 for Installed Applications中描述的步骤,我已经能够获得我的应用程序的授权代码。Google API OAuth2 - 从授权令牌获取刷新令牌

我已经注册了我的应用程序在谷歌开发者控制台中的OAuth 2.0客户端ID: http://image.prntscr.com/image/bcda26f2ee12463e80e4fdd9401380da.png

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

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

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

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

http://image.prntscr.com/image/a506d2095be1472aa1807a52b01ab1f1.png

我已经能够得到一个授权码我的手,用下面的请求(以下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在我的浏览器,它重定向我到此页:

http://image.prntscr.com/image/64ccfc9a63be4cb985163c0e3ba0c8ef.png

这样我已获得授权代码,从理论上,可以为一个refresh_token和交换的access_token。

我试图模仿的要求,谷歌的OAuth 2.0交换了refresh_token授权码和的access_token当游乐场的作用:

http://image.prntscr.com/image/54e7e7da18f044c3a86e2a05b51ba830.png

它发出了一个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引发“Missing scheme”错误。这在我看来并不奇怪,因为我的应用程序类型是“其他”,而您无法授权使用该类型的重定向URI

我曾尝试OAuth2ForDevices(这是正是我想要的),但我不能使用谷歌的电子表格。

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

回答

4

我想通了。

使用此要求:

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 

如果不使用 “金塔:IETF:WG:OAuth的:2.0:OOB” 作为REDIRECT_URI,这是行不通的。这不是在OAuth2InstalledApp Guide说(它使用“https://oauth2-login-demo.appspot.com/code”为例为REDIRECT_URI,这让我感到困惑)。

简短的回答:用 “金塔:IETF:WG:OAuth的:2.0:OOB” 为REDIRECT_URI

0

使用您用于呼叫到同一REDIRECT_URI:

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

谷歌不会进行任何进一步的请求发送到URI,但我相信它使用它进行匹配的一些小的安全性。