Ad

Google Analytics API Request Works With Insomnia/postman But Don't From A Web App

- 1 answer

I want to fetch data from google-analytics from angular web. I have made the OAuth2 authentication to get the access token, and when I do the request from the web it response as unauthorized. But when I do the request from Postman it works fine.

The OAuth2 authentication is implemented like this article from google-developers: https://developers.google.com/identity/protocols/OAuth2UserAgent

here is the request from the web:

const bod = {
      reportRequests: [
        {
          viewId: '--MY-ID--',
          dateRanges: [
            {
              startDate: '30daysAgo',
              endDate: 'yesterday',
            },
          ],
          metrics: [
            {
              expression: '--METRIC1--',
            },
            {
              expression: '--METRIC2--',
            },
          ],
          dimensions: [
            {
              name: '--DIMENSION--',
            },
          ],
        },
      ],
    };

    var res = this.http.post('https://analyticsreporting.googleapis.com/v4/reports:batchGet?access_token=' + token, bod);

This is the result I get from the web app

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}
Ad

Answer

Solved, I was sending two tokens, one in the query params like I described in the question, and other in the requests headers (this one is for authentication in the backend). In the request interceptor, I verify that the URL is to the backend, and not to the google analytics API, in the second case I just don't add the Bearer token.

I suppose if Google receives two tokens (one in the query and other as a header) they use the one in the header, so I got unauthenticated.

Ad
source: stackoverflow.com
Ad