本文介绍了oauth2Client.getToken缺少refresh_token的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有两条路线的小型快递服务器。然后它将json标记写入文件(我知道非常不安全)。出于某种原因,没有 refresh_token 。在文档中,离线 access_type 的评论获得 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 () {})


推荐答案

refresh_token 仅在用户最初使用其帐户授权您的应用时发送。所以 getToken 函数只在第一次返回它(因为你应该存储它)。将 approval_prompt:force添加到 generateAuthUrl 选项中,我每次都可以获取它。

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.

这篇关于oauth2Client.getToken缺少refresh_token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 19:19