获取刷新令牌并交换访问令牌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();

选择器具有.setoAuthToken(access_token)方法,该方法将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",params: {
      client_id: driveClientId,client_secret: driveClientSecret,refresh_token: googleOAuthToken,grant_type: "refresh_token"
    } 
 });
  
let accessToken = tokenRequest.data["access_token"];