Generate OAuth2.0 refresh token

Stay organized with collections Save and categorize content based on your preferences.

Generate an OAuth2 refresh token

/**
 * This script allows the stepping through of the Authorization Code Grant in
 * order to obtain a refresh token.
 *
 * This script uses the out-of-band redirect URI, which is not part of the
 * OAuth2 standard, to allow not redirecting the user. If this does not work
 * with your API, try instead the OAuth playground:
 * https://developers.google.com/oauthplayground/
 *
 * Execute script twice:
 * Execution 1: will result in a URL, which when placed in the browser will
 * issue a code.
 * Execution 2: place the code in "CODE" below and execute. If successful a
 * refresh token will be printed to the console.
 */
const CLIENT_ID = 'ENTER_CLIENT_ID';
const CLIENT_SECRET = 'ENTER_CLIENT_SECRET';

// Enter required scopes, e.g. ['https://www.googleapis.com/auth/drive']
const SCOPES = ['ENTER_SCOPES'];

// Auth URL, e.g. https://accounts.google.com/o/oauth2/auth
const AUTH_URL = 'ENTER_AUTH_URL';
// Token URL, e.g. https://accounts.google.com/o/oauth2/token
const TOKEN_URL = 'ENTER_TOKEN_URL';

// After execution 1, enter the OAuth code inside the quotes below:
let CODE = '';

function main() {
  if (CODE) {
    generateRefreshToken();
  } else {
    generateAuthUrl();
  }
}

/**
 * Creates the URL for pasting in the browser, which will generate the code
 * to be placed in the CODE variable.
 */
function generateAuthUrl() {
  const payload = {
    scope: SCOPES.join(' '),
    // Specify that no redirection should take place
    // This is Google-specific and not part of the OAuth2 specification.
    redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
    response_type: 'code',
    access_type: 'offline',
    client_id: CLIENT_ID
  };
  const options = {payload: payload};
  const request = UrlFetchApp.getRequest(AUTH_URL, options);
  console.log(
      'Browse to the following URL: ' + AUTH_URL + '?' + request.payload);
}

/**
 * Generates a refresh token given the authorization code.
 */
function generateRefreshToken() {
  const payload = {
    code: CODE,
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    // Specify that no redirection should take place
    // This is Google-specific and not part of the OAuth2 specification.
    redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
    grant_type: 'authorization_code'
  };
  const options = {method: 'POST', payload: payload};
  const response = UrlFetchApp.fetch(TOKEN_URL, options);
  const data = JSON.parse(response.getContentText());
  if (data.refresh_token) {
    const msg = `Success! Refresh token: ${data.refresh_token}` +
      `

The following may also be a useful format for pasting into your ` +
      `script:

` +
      `const CLIENT_ID = '${CLIENT_ID}';
` +
      `const CLIENT_SECRET = '${CLIENT_SECRET}';
` +
      `const REFRESH_TOKEN = '${data.refresh_token};'`;
    console.log(msg);
  } else {
    console.log(
        'Error, failed to generate Refresh token: ' +
        response.getContentText());
  }
}