ThomasReggi
ThomasReggi

Reputation: 59345

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)
  }).catch(function(err){
    return res.redirect("/google")
  })
})

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

Upvotes: 11

Views: 6552

Answers (2)

Sudhanshu Sharma
Sudhanshu Sharma

Reputation: 192

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'
});

Upvotes: 3

ThomasReggi
ThomasReggi

Reputation: 59345

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.

Upvotes: 21

Related Questions