Home > database >  how to Access Google drive api without expiration or revoking refresh token Or any other solution
how to Access Google drive api without expiration or revoking refresh token Or any other solution

Time:11-09

For the past two months I have been encountered a problem of expiration of refresh token , I have to generate new refresh token from google Oauth playground every 3rd-4rth day . I need permanent solution that I can access google drive api with infinite time .

This is the auth code I have written in node js .

const { google } = require('googleapis');
const async = require('async')

const CLIENT_ID = process.env.GOOGLE_CLIENT_KEY;
const CLIENT_SECRET = process.env.GOOGLE_SECRET_KEY;
const REDIRECT_URI = https://developers.google.com/oauthplayground
const REFRESH_TOKEN = process.env.REFRESH_TOKEN;
const oauth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URI
);

oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

const drive = google.drive({
    version: 'v3',
    auth: oauth2Client,
});

async function uploadFile(res) {
  try {
    const response = await drive.files.create({
      requestBody: {
        name: `${res}.docx`,
        mimeType: 'application/vnd.google-apps.document',
      },
      media: {
        mimeType: 'application/vnd.google-apps.document',
        body: "you can write in a body field in backend",
      },
    });
    return response.data.id
  } catch (error) {
    console.log(error);
  }
}

CodePudding user response:

Google oauth2 playground is intended for testing only. It is not intended to be a prodctuion solution.

Your should set up your code to request authorization once and store the token. It will then be able to request a new access token when ever it needs. see node.js quickstart

const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
 * Reads previously authorized credentials from the save file.
 *
 * @return {Promise<OAuth2Client|null>}
 */
async function loadSavedCredentialsIfExist() {
  try {
    const content = await fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch (err) {
    return null;
  }
}

/**
 * Serializes credentials to a file comptible with GoogleAUth.fromJSON.
 *
 * @param {OAuth2Client} client
 * @return {Promise<void>}
 */
async function saveCredentials(client) {
  const content = await fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content);
  const key = keys.installed || keys.web;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: key.client_id,
    client_secret: key.client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  await fs.writeFile(TOKEN_PATH, payload);
}

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
  let client = await loadSavedCredentialsIfExist();
  if (client) {
    return client;
  }
  client = await authenticate({
    scopes: SCOPES,
    keyfilePath: CREDENTIALS_PATH,
  });
  if (client.credentials) {
    await saveCredentials(client);
  }
  return client;
}

While your app is in the testing phase your refresh token will only be good for seven days. You will need to set your app to production and then your refresh token will stope expiring.

  • Related