google-oauth - 获取刷新令牌并交换访问令牌 Google Drive Javascript API?
问题描述
我在前端使用 Google Drive API 和 Google Picker API。我的目标是让用户授权使用他们的驱动器帐户,然后能够在需要时随时调用 Google Picker API,而无需重新授权他们的驱动器。
// Authorizing client initially (I only want them to have to do this once)
await gapi.load("client:auth2", async () => {
clientInit = window.gapi.auth2.init({
client_id: driveClientId,
scope: driveScope,
});
await gapi.client.load('drive', 'v2', () => { handleAuthResult(clientInit) });
});
// Setting the access token (expires in 3600s)
async handleAuthResult(authResult) {
let signInResponse = await authResult.signIn();
let googleOAuthToken = signInResponse.wc["access_token"];
}
// Creating picker
new google.picker.PickerBuilder()
.addView(docsView)
.setOAuthToken(googleOAuthToken)
.setCallback(drivePickerCallback)
.build();
选择器具有将 access_token 作为参数的 .setOAuthToken(access_token) 方法。您在授权驱动器后最初获得的那个会在 1 小时内过期,并且它没有给我一个刷新令牌来获取另一个访问令牌。signInResponse.wc 不包含刷新令牌。
我对如何获取此刷新令牌以及如何使用它来获取访问令牌感到困惑,文档不是很清楚。
解决方案
好的,所以我能够使用 .grantOfflineAccess() 方法解决这个问题。这将返回一个授权代码,该代码可用于通过向https://www.googleapis.com/oauth2/v4/token发出 POST 请求来交换刷新令牌。
// Getting refresh token
let offlineAccess = await signInResponse.grantOfflineAccess();
// Authorization code can be used to exchange for a refresh token
let refreshAccessCode = offlineAccess.code;
let tokenRequest = await axios.request({
method: 'post',
url: "https://www.googleapis.com/oauth2/v4/token",
headers: {"content-type": "application/x-www-form-urlencoded"},
params: {
code: refreshAccessCode,
client_id: this.driveClientId,
client_secret: this.driveClientSecret,
redirect_uri: "postmessage",
grant_type: "authorization_code"
}
});
let googleOAuthToken = tokenRequest.data["refresh_token"];
现在您有了刷新令牌,您可以通过发出另一个 POST 请求将其交换为访问令牌,如下所示:
// Exchanging refresh token for access code
let tokenRequest = await axios.request({
method: 'post',
url: "https://oauth2.googleapis.com/token",
headers: {"content-type": "application/x-www-form-urlencoded"},
params: {
client_id: driveClientId,
client_secret: driveClientSecret,
refresh_token: googleOAuthToken,
grant_type: "refresh_token"
}
});
let accessToken = tokenRequest.data["access_token"];
推荐阅读
- ruby-on-rails - 设计确认电子邮件似乎已发送但未收到
- .net - 使用 WiX 安装程序在 Windows 10 中启用 .NET Framework 3.5
- python-3.x - 有没有办法创建从 pyinstaller --onefile 生成的单个可执行 exe 文件的 MSI 包?
- ios - iOS重定向到特定的密码重置页面?
- powershell - 将从 select-object 返回的单个元素转换为 json 字符串数组
- database - Laravel 游标会锁定表吗?
- firebase - 如何从firebase下载图像?云火库?Forbebase 存储?
- node.js - 如何使用节点 js 从 mongo dB 获取日期?
- c# - 根据 List 中的字符串值进行过滤
表中的列 Entity Framework Core - android - Android 测试:未找到测试