oauth2Client.getToken missing refresh_token

I have a small express server that has two routes. Then it writes the json tokens to a file (I know very insecure). For some reason there’s no refresh_token. In the docs theres a comment that offline for access_type gets refresh_token, which is set and it’s still not working

access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)

Here’s the express server, sorry if the promises throw anyone off.

var Promise = require("bluebird")
var express = require('express')
var app = express()

var google = require('googleapis')
var OAuth2 = google.auth.OAuth2
var clientSecrets = require("./client_secrets.json")
var oauth2Client = new OAuth2(clientSecrets.web.client_id, clientSecrets.web.client_secret, clientSecrets.web.redirect_uris[0]);
oauth2Client.getToken = Promise.promisify(oauth2Client.getToken)

var fs = Promise.promisifyAll(require("fs"))

app.get('/google', function (req, res) {
  var url = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: "https://www.googleapis.com/auth/drive"
  return res.redirect(url)

app.get('/oauth2callback', function (req, res) {
  return oauth2Client.getToken(req.query.code).then(function(tokens){
    fs.writeFileAsync("./tokens.json", JSON.stringify(tokens), "utf8");
    return res.json(tokens)
    return res.redirect("/google")

var server = app.listen(3000, function () {})

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The refresh_token is only sent when the user initially authorizes your app with their account. So it the getToken function only returns it the first time (because you should store it). Added approval_prompt: "force" to the generateAuthUrl options, and I can get it every time.

Solution 2

To be more precise, you only get a refresh_token back when the user saw the consent screen, AKA the list of scopes and the "Accept" button. Users will see this screen the first time they are asked to grant access, but upon subsequent trips through the OAuth flow that screen is skipped (assuming they haven’t revoked access). However, you can force the user to see the consent screen again by passing &prompt=consent in the authorization URL:

var url = oauth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: scopes,
  prompt: 'consent'

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply