belgacea belgacea - 2 months ago 49
Node.js Question

How to authenticate to Google Analytics Reporting API v4

I'm into trouble to authenticate to Google Analytics Reporting API v4 using Node.js client library.
I tried all methods, starting with JWT (Service Tokens : JSON & P12), API Keys and OAuth 2.0, but i've never successfully been authenticated.

I activated the API in my developer console, created IDs and granted the rights on my google analytics property and view.
I successfully get authorization and an access token for my service account but i don't know how to use it to authenticate to Analytics Reporting API v4.

I'm stuck in front of an 401 error message : "The request does not have valid authentication credentials".
I tried using JWT impersonate user, but then the service account is unauthorized.

Using Node.js client library and JWT Authentication :

var google = require('googleapis.js');

var viewID = 'XXXXXXXXX'; // Google Analytics view ID
var key = require('service_account.json'); // Service account

var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
var oauth2Client = new google.auth.OAuth2();

jwtClient.authorize(function(err, result) {
if (err) {
console.log('Unauthorize');
console.log(err);
return;
}

oauth2Client.setCredentials({
access_token: result.access_token
});

//Need to authenticate somewhere near here
var analytics = google.analyticsreporting('v4');
//Or here

var req = {
reportRequests: [
{
viewId: viewID,
dateRanges: [
{
startDate: '2016-05-01',
endDate: '2016-06-30',
},],
metrics: [
{
expression: 'ga:users',
}, {
expression: 'ga:sessions',
},],
},],
};

//Maybe here
analytics.reports.batchGet(req,
function(err, response) {
if (err) {
console.log('Fail');
console.log(err);
return;
}
console.log('Success');
console.log(response);
}
);
});


Previous releases of Node.js client library seems to have a method to specify the client but it disappeared, maybe deprecated.

withAuthClient(oauth2Client)


I've tried to pass the client or the token in the API call or in the request, but none works.

google.analyticsreporting({ version: 'v4', auth: oauth2Client });
google.analyticsreporting({ version: 'v4', access_token: result.access_token });


Maybe it's a noob question but i don't know how to do it, i don't see anything related to Analytics Reporting v4 authentication in the google api or client library documentation, and most examples i found uses Google Analytics API v3.

If someone managed to successfully authenticate to Analytics Reporting API v4, please help :/

Answer

Found out what I was missing :

  • Google APIs Client Library "Options" :

    google.options({ auth: oauth2Client }); //this one is not very optional
    
  • Unlike Google Analytics Reporting API v4 documentation, queries using the client library must have headers to specify a client for each requests (thanks to CVarisco who notice that, client library documentation isn't really accurate..) :

    var request ={
        'headers': {'Content-Type': 'application/json'},
        'auth': oauth2Client,
        'resource': req,
    };
    
Comments