google api的刷新令牌在nodejs中无法正常工作

时间:2016-05-17 21:28:02

标签: node.js google-api-nodejs-client

我正在使用google api nodejs,我尝试从google Anaytics获取数据

var google = require('googleapis');
var OAuth2Client = google.auth.OAuth2;
var CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxx';
//var REDIRECT_URL = 'http://yieldops.co/oauth2Callback';
var REDIRECT_URL = 'http://localhost:8000/oauth2Callback';
var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET,REDIRECT_URL);

var credentials={}
credentials.expiry_date= "1463514280558",
credentials['refresh_token']="aaaaaaaaa"
credentials['access_token']="aaaaaaaaaaaaaaa"
oauth2Client.setCredentials(credentials)

var gauth = {
'auth': outh2Client,
'ids': 'ga:101' ,
'start-date': '2016-01-01',
'end-date': 'today',
'metrics': 'ga:impressions,ga:sessions,ga:pageviews',
'dimensions': 'ga:date'
}

analytics.data.ga.get(gauth, function (err, gaData) {
console.log("err 1234",err)
console.log("gaData ",gaData)
//console.log("ga",Object.keys(gaData))
})

注意 现在的问题是,如果访问令牌没有过期,那么它会给我数据,如果访问令牌过期,那么它会给我 400错误无效授权。如果我从凭证中删除expiry_date,那么它会给我错误

{ [Error: Invalid Credentials]
code: 401,
errors: 
[ { domain: 'global',
reason: 'authError',
message: 'Invalid Credentials',
locationType: 'header',
location: 'Authorization' } ] }

2 个答案:

答案 0 :(得分:3)

access_token的到期时间为1小时。您必须在过期时刷新access_token。

oauth2Client.refreshAccessToken(function(err, tokens) {
  // your access_token is now refreshed and stored in oauth2Client
  // store these new tokens in a safe place (e.g. database)
});

你能找到here

吗?

答案 1 :(得分:0)

access_token到期后,无需显式刷新令牌。 Oauth2客户端将自动刷新令牌,并重播请求,前提是您获得refresh_token的第一授权,请在OAuth2客户端凭据中设置此refresh_token,如以下代码所示< / p>

const {tokens} = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens);

还是,您要手动刷新access_token,然后使用以下代码。

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
});

OR

oauth2Client.refreshAccessToken((err, tokens) => {
  // your access_token is now refreshed and stored in oauth2Client
  // store these new tokens in a safe place (e.g. database)
});

参考:

  1. https://github.com/googleapis/google-api-nodejs-client/blob/c00d1892fe70d7ebf934bcebe3e8a5036c62440c/README.md#making-authenticated-requests
  2. https://github.com/googleapis/google-api-nodejs-client/blob/c00d1892fe70d7ebf934bcebe3e8a5036c62440c/README.md#manually-refreshing-access-token
  3. https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens