I'm having trouble authenticating the Google Analytics v4 Reporting API using the Node.js client library . I tried all methods starting with JWT (service tokens: JSON and P12), API Keys and OAuth 2.0, but I have never been authenticated successfully.
I activated the API in my developer console, created identifiers and granted the rights to my property and viewing Google Analytics. I successfully receive authorization and access token for my service account, but I donโt know how to use it for authentication in the Google Analytics v4 reporting API.
I am stuck in front of error message 401: "The request does not have valid credentials." I tried using JWT, impersonating the 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 the Node.js client library seem to have a way of specifying the client, but it has disappeared, possibly outdated.
withAuthClient(oauth2Client)
I tried to pass a client or token in an API call or in a request, but no one works.
google.analyticsreporting({ version: 'v4', auth: oauth2Client }); google.analyticsreporting({ version: 'v4', access_token: result.access_token });
Maybe this is a noob question, but I donโt know how to do it, I donโt see anything related to the authentication of Google Analytics v4 in the google api documentation or client library, and most of the examples I found use the Google Analytics v3 API.
If someone was able to successfully authenticate to the Google Analytics v4 Reporting API, please help: /