【问题标题】:Google Analytics - invalid_grant: Invalid JWT SignatureGoogle Analytics - invalid_grant:无效的 JWT 签名
【发布时间】:2018-10-04 10:13:26
【问题描述】:

我需要通过 Google Analytics 授权才能获取响应数据。

var google = require('googleapis'), 
  q = require('q'), 
  SERVICE_ACCOUNT_EMAIL = '838823084353-cjjoiv9di67fuh7geqgggociibataf9v@developer.gserviceaccount.com', 
  SERVICE_ACCOUNT_KEY_FILE = __dirname + '/google-services-private-key.pem';
  var def = q.defer(); 
  var gAnalytics = google.analytics('v3'); 
  var authClient = new google.auth.JWT( SERVICE_ACCOUNT_EMAIL, SERVICE_ACCOUNT_KEY_FILE, null, ['https://www.googleapis.com/auth/analytics.readonly']); 
  console.log(authClient) 

  authClient.authorize(function (err, tokens) { 
    if (err) { 
      console.log("err is: " + err, tokens); 
      return; 
    } 

但是授权失败

遇到错误

JWT { 传输器:DefaultTransporter {},clientId_:未定义, clientSecret_:未定义,redirectUri_:未定义,选择:{},
凭据:{ refresh_token:'jwt-placeholder',expiry_date:1 },
电子邮件: '838823084353-cjjoiv9di67fuh7geqgggociibataf9v@developer.gserviceaccount.com', 密钥文件: '/home/aaa/Desktop/ampretailer/server/google-services-private-key.pem', 键:空,范围:[ 'https://www.googleapis.com/auth/analytics.readonly' ],主题: 未定义,gToken:[功能:GoogleToken]} 错误是:错误: invalid_grant:无效的 JWT 签名。 { access_token:空, token_type: 'Bearer', expiry_date:null }

【问题讨论】:

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


    【解决方案1】:

    我建议您尝试使用 Google Analytics v4 而不是 v3,因为使用 V3 您将无法访问许多维度和指标。

    'use strict';
    
    const { google } = require('googleapis');
    const sampleClient = require('../sampleclient');
    
    const analyticsreporting = google.analyticsreporting({
      version: 'v4',
      auth: sampleClient.oAuth2Client
    });
    
    async function runSample () {
      const res = await analyticsreporting.reports.batchGet({
        resource: {
          reportRequests: [{
            viewId: '65704806',
            dateRanges: [
              {
                startDate: '2018-03-17',
                endDate: '2018-03-24'
              }, {
                startDate: '14daysAgo',
                endDate: '7daysAgo'
              }
            ],
            metrics: [
              {
                expression: 'ga:users'
              }
            ]
          }]
        }
      });
      console.log(res.data);
      return res.data;
    }
    
    // if invoked directly (not tests), authenticate and run the samples
    if (module === require.main) {
      const scopes = ['https://www.googleapis.com/auth/analytics'];
      sampleClient.authenticate(scopes)
        .then(c => runSample())
        .catch(e => console.error);
    }
    
    // export functions for testing purposes
    module.exports = {
      runSample,
      client: sampleClient.oAuth2Client
    };
    

    analyticsReporting/batchGet.js 窃取的代码

    服务帐户 - 要使用基于服务帐户的示例,请在云开发者控制台中创建一个新的服务帐户,并将文件保存为示例目录中的 jwt.keys.json。

    'use strict';
    
    const {google} = require('googleapis');
    const path = require('path');
    
    /**
     * The JWT authorization is ideal for performing server-to-server
     * communication without asking for user consent.
     *
     * Suggested reading for Admin SDK users using service accounts:
     * https://developers.google.com/admin-sdk/directory/v1/guides/delegation
     *
     * See the defaultauth.js sample for an alternate way of fetching compute credentials.
     */
    async function runSample () {
      // Create a new JWT client using the key file downloaded from the Google Developer Console
      const client = await google.auth.getClient({
        keyFile: path.join(__dirname, 'jwt.keys.json'),
        scopes: 'https://www.googleapis.com/auth/analytics.readonly'
      });
    
      // Obtain a new drive client, making sure you pass along the auth client
      const analyticsreporting = google.analyticsreporting({
        version: 'v4',
        auth: client
      });
    
      // Make an authorized request to list Drive files.
      const res = = await analyticsreporting.reports.batchGet({
        resource: {
          reportRequests: [{
            viewId: '65704806',
            dateRanges: [
              {
                startDate: '2018-03-17',
                endDate: '2018-03-24'
              }, {
                startDate: '14daysAgo',
                endDate: '7daysAgo'
              }
            ],
            metrics: [
              {
                expression: 'ga:users'
              }
            ]
          }]
        }
      });
      console.log(res.data);
    
      return res.data;
    }
    
    if (module === require.main) {
      runSample().catch(console.error);
    }
    
    // Exports for unit testing purposes
    module.exports = { runSample };
    

    samples/jwt.js 窃取的代码

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 2020-09-01
      • 2016-09-23
      • 2018-06-14
      • 2023-03-03
      • 1970-01-01
      • 2016-12-29
      • 2020-01-21
      • 2019-11-09
      相关资源
      最近更新 更多