belgacea
belgacea

Reputation: 1164

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 :/

Upvotes: 9

Views: 6714

Answers (3)

Ali Ann
Ali Ann

Reputation: 169

This is how I was able to do it:

You will need to create your credentials for your application here: https://console.developers.google.com/apis. This will give you a client ID and client secret (Note - please make sure https://developers.google.com/oauthplayground as an authorized redirect uri). Then go to https://developers.google.com/oauthplayground to create authorization tokens. The access token you are given should be sent to the Google API through the header and value: "Authorization" : "Bearer {{AccessToken}}". If your token expires, you can retrieve a new one by hitting the OAUTH api (https://www.googleapis.com/oauth2/v4/token), sending refresh_token, client_id, client_secret, grant_type and access_type in the query and 'user-agent': 'google-oauth-playground' in the header.

If you get stuck, implement the google API the way they describe here: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js. You can then use developer tools in a browser to see exactly what values are being sent where.

Hope this helps. :)

Upvotes: 0

Rob Knights
Rob Knights

Reputation: 247

Note also that the recommended way to do authentication with a service account on server-side is using auth.getApplicationDefault.

https://developers.google.com/identity/protocols/application-default-credentials

We recommend using Application Default Credentials in any of the following circumstances:
...snip...
- You are accessing APIs with data associated with a cloud project or otherwise scoped to the whole application rather than personal user data. For calls involving user data, it is instead best to use an authorization flow where the end user gives explicit consent for access (see Using OAuth 2.0 to Access Google APIs).

Upvotes: 0

belgacea
belgacea

Reputation: 1164

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,
    };
    

Upvotes: 9

Related Questions