6
votes

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 () {})
1

1 Answers

12
votes

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.