假设我有一个需要在后台服务中访问Drive文件的Web应用程序。它将拥有自己正在访问的文件,或者在所有者共享文档的Google帐户中运行。
我知道我的应用程序需要一个刷新令牌,但我不想编写代码来获取它,因为我只会做一次。
NB。这不是使用服务帐户。该应用将在传统的Google帐户下运行。在某些情况下,服务帐户是一种有效的方法。但是,使用Oauth Playground模拟应用程序的技术可以节省大量的冗余工作,并适用于不支持与服务帐户共享的任何API。
这可以通过https://developers.google.com/oauthplayground的Oauth2游乐场完成
脚步:-
Credentials/Create Credentials/OAuth Client Id
然后选择Web application
您的应用程序现在可以无人值守运行,并使用https://developers.google.com/accounts/docs/OAuth2WebServer#offline描述的Refresh Token来获取访问令牌。
NB。请注意,Google可以过期刷新令牌,这意味着您需要重复步骤5以获得新的刷新令牌。当您尝试使用刷新令牌时,此症状将是返回的无效授权。
NB2。如果您想要一个可以访问您自己的(并且只有您自己的)云端硬盘帐户的网络应用程序,而无需编写只能运行一次的授权代码,这种方法效果很好。只需跳过步骤1,并在步骤6中将“my.drive.app”替换为您自己的电子邮件地址。确保您知道刷新令牌被盗后的安全隐患。
请参阅下面的Woody评论链接到这个谷歌视频https://www.youtube.com/watch?v=hfWe1gPCnzc
. . .
这是一个快速JavaScript例程,演示如何使用OAuth Playground中的Refresh Token列出一些Drive文件。您只需将其复制粘贴到Chrome开发者控制台,或者使用节点运行它。当然提供你自己的凭据(下面的都是假的)。
function get_access_token_using_saved_refresh_token() {
// from the oauth playground
const refresh_token = "1/0PvMAoF9GaJFqbNsLZQg-f9NXEljQclmRP4Gwfdo_0";
// from the API console
const client_id = "559798723558-amtjh114mvtpiqis80lkl3kdo4gfm5k.apps.googleusercontent.com";
// from the API console
const client_secret = "WnGC6KJ91H40mg6H9r1eF9L";
// from https://developers.google.com/identity/protocols/OAuth2WebServer#offline
const refresh_url = "https://www.googleapis.com/oauth2/v4/token";
const post_body = `grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}&refresh_token=${encodeURIComponent(refresh_token)}`;
let refresh_request = {
body: post_body,
method: "POST",
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
}
// post to the refresh endpoint, parse the json response and use the access token to call files.list
fetch(refresh_url, refresh_request).then( response => {
return(response.json());
}).then( response_json => {
console.log(response_json);
files_list(response_json.access_token);
});
}
// a quick and dirty function to list some Drive files using the newly acquired access token
function files_list (access_token) {
const drive_url = "https://www.googleapis.com/drive/v3/files";
let drive_request = {
method: "GET",
headers: new Headers({
Authorization: "Bearer "+access_token
})
}
fetch(drive_url, drive_request).then( response => {
return(response.json());
}).then( list => {
console.log("Found a file called "+list.files[0].name);
});
}
get_access_token_using_saved_refresh_token();
让我为pinoyyid的优秀答案添加另一条路径(这对我不起作用 - 弹出重定向错误)。
您也可以直接使用HTTP REST API,而不是使用OAuthPlayground。因此,与pinoyyid的答案的不同之处在于我们会在本地做事。按照pinoyyid的回答中的步骤1-3。我引用他们的话:
现在,将以下内容添加到您的凭据中,而不是操场:
授权的JavaScript来源:http://localhost(我不知道这是否是必需的,但只是这样做。) 授权重定向URI:http://localhost:8080
截图(德文):
确保通过下面的蓝色按钮实际保存更改!
现在,您可能希望使用GUI来构建HTTP请求。我使用Insomnia,但你可以使用Postman或普通cURL。我推荐Insomnia,因为它可以让你轻松浏览同意屏幕。
使用以下参数构建新的GET请求:
URL: https://accounts.google.com/o/oauth2/v2/auth
Query Param: redirect_uri=http://localhost:8080
Query Param: prompt=consent
Query Param: response_type=code
Query Param: client_id=<your client id from OAuth credentials>
Query Param: scope=<your chosen scopes, e.g. https://www.googleapis.com/auth/drive.file>
Query Param: access_type=offline
如果您选择的工具不能自动处理URL编码,请确保自己正确处理。
在您发出请求之前,请设置一个网络服务器来监听http://localhost:8080
。如果您安装了node和npm,则运行npm i express
,然后创建一个index.js
:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('ok');
console.log(req)
});
app.listen(8080, function () {
console.log('Listening on port 8080!');
});
并通过node index.js
运行服务器。我建议要么不记录整个req
对象,要么运行node index.js | less
,因为完整输出将是巨大的。
其他语言也有非常简单的解决方案。例如。在8080 php -S localhost:8080
上使用PHP的内置Web服务器。
现在解雇你的请求(在Insomnia中),你应该会提示你登录:
使用您的电子邮件和密码登录并确认同意屏幕(应包含您选择的范围)。
返回终端并检查输出。如果你记录整个事情向下滚动(例如pgdown in less),直到你看到一行code=4/...
。
复制该代码;它是您要为访问和刷新令牌交换的授权码。不要复制太多 - 如果有&符号&
不复制它或之后的任何东西。 &
分隔查询参数。我们只想要code
。
现在设置一个HTTP POST请求,指向https://www.googleapis.com/oauth2/v4/token
作为表单URL编码。在Insomnia中你可以点击它 - 在其他工具中你可能需要自己设置标题为Content-Type: application/x-www-form-urlencoded
。
添加以下参数:
code=<the authorization code from the last step>
client_id=<your client ID again>
client_secret=<your client secret from the OAuth credentials>
redirect_uri=http://localhost:8080
grant_type=authorization_code
再次,确保编码是正确的。
触发您的请求并检查服务器的输出。在响应中,您应该看到一个JSON对象:
{
"access_token": "xxxx",
"expires_in": 3600,
"refresh_token": "1/xxxx",
"scope": "https://www.googleapis.com/auth/drive.file",
"token_type": "Bearer"
}
您可以立即使用access_token
,但它只能有效一小时。请注意刷新令牌。这是您可以随时*交换新访问令牌的那个。
*
如果用户更改密码,撤销访问权限,6个月无效等,您将不得不重复此过程。
快乐OAuthing!