首页 > 解决方案 > 获取刷新令牌并交换访问令牌 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 不包含刷新令牌。

我对如何获取此刷新令牌以及如何使用它来获取访问令牌感到困惑,文档不是很清楚。

标签: google-oauthaccess-tokendriverefresh-tokengoogle-api-js-client

解决方案


好的,所以我能够使用 .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"];

推荐阅读