我正在尝试在我的网站中获取我的谷歌相册。现在,我正在使用 Google Photos API。
问题是,我可以成功获取访问令牌,但使用访问令牌调用 google API 失败,并出现未经身份验证的错误。
现在,事情变得更奇怪了...... 当我在邮递员中运行相同的步骤,获取访问令牌并使用该访问令牌调用 google photos API 时,它可以正常工作。 另外,如果我在代码中使用邮递员生成的访问令牌,它可以工作,但是在邮递员中使用我的程序中的访问令牌,邮递员会失败。
所以我不确定哪里出了问题。如果有任何帮助,我将不胜感激。请有人帮忙。
以下是我的代码
我使用
https://www.googleapis.com/oauth2/v4/token
创建访问令牌
fetch("https://www.googleapis.com/oauth2/v4/token", {
method: "POST",
headers: {
"Content-Type": "text/plain",
},
body: JSON.stringify({
grant_type: "refresh_token",
client_id: "<client_id>",
client_secret: "<client_secret>",
refresh_token: "<refresh_token>",
}),
})
现在当然要获取客户端 ID 和秘密,我们创建一个 google 开发帐户,创建一个应用程序,并在其中创建 oauth2 凭据,然后我就得到了它。 同样在应用程序中,您可以搜索想要使用的所需 API 并允许使用。就我而言,我允许使用照片和驱动 API 为了获取刷新令牌,我去了 oauth 游乐场并从那里生成它。现在 oauth Playground 已经涵盖了用户同意部分。在 oauth 游乐场中,我还为驱动器和照片 API 选择了正确的范围
现在我知道我的所有步骤都是正确的,因为我得到的响应具有正确的架构,包括 access_token、到期日和我上面提到的正确范围。
问题出在这里之后的部分。当我尝试如下使用此令牌时
const Authorization = `Bearer ${token}`;
const res = await fetch("https://photoslibrary.googleapis.com/v1/albums", {
headers: {
"Content-Type": "application/json",
Authorization,
},
});
返回错误
{
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
尝试一下,您需要将其定义为授权标头
headers: {
"Content-Type": "application/json",
“Authorization“: Authorization,
},