过去,我使用this question的答案来设置自动脚本,以将新工作表推送到Google表格。我现在正试图做同样的事情来检索Google相册信息。
我使用OAuth2游乐场获取刷新令牌,因为这需要交互式批准部分,而自动化脚本无法使用该部分。在我的node.js代码中,我具有此功能来获取新令牌:
function OAuth2() {
// from the oauth playground
const refresh_token = <<refresh token>>
// from the API console
const client_id = <<client id>>
// from the API console
const client_secret = <<secret>>
// 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: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return fetch(refresh_url, refresh_request).then( response => {
return(response.json());
}).then( response_json => {
console.log(response_json)
return response_json.access_token
})
}
这一切都在以前的项目中起作用,我只是将代码复制/粘贴到新项目中。但是,当我调用此函数时,出现此错误:
{ error: 'unauthorized_client', error_description: 'Unauthorized' }
我还尝试了直接从OAuth2游乐场使用访问令牌,但是它也不起作用:
[Symbol(Response internals)]: {
url: 'https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100',
status: 401,
statusText: 'Unauthorized',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
但是,我没有问题,可以使用刚刚生成并插入到脚本中的相同令牌直接从OAuth2游乐场运行此请求。但这不是一个合适的解决方案-我需要在脚本中运行它,因为我需要进行数百次API调用。
我还看到了this question,显然可以在其中获取刷新的访问令牌,我认为这是无法从命令行脚本获得的。但是,提供的答案使用“ redirect_uri = REDIRECT_URL”,我不知道此REDIRECT_URL应该是什么。我的理解是,它应该指向我正在服务的页面,但是没有服务器,它是从命令行运行的。我尝试使用OAuth2游乐场重定向网址进行抓取:
const access_url = `https://accounts.google.com/o/oauth2/auth?redirect_uri=${encodeURIComponent("https://developers.google.com/oauthplayground")}&response_type=code&client_id=${encodeURIComponent(client_id)}&scope=${encodeURIComponent("https://www.googleapis.com/auth/photoslibrary.readonly")}&approval_prompt=force&access_type=offline`
但这会返回400错误的请求。
更新:我试图在OAuth2 Playground中输入自己的OAuth凭据。但这给了我以下错误:
400. That’s an error.
Error: redirect_uri_mismatch
更新2:
我按照here的说明替换了Google Photos范围。我将URL粘贴到浏览器中并授予权限,然后从成功的身份验证中获得了访问令牌。但是,当我尝试在我的应用程序中使用它时,我得到了401未经授权!如果我使用刷新令牌来获取新的访问令牌,则它可以工作,但是当我尝试使用此令牌时,我也会得到401未经授权!为什么当我刚刚成功授权时,我是未经授权的?!