0
votes

I need to do a POST request to get the access token from Google Analytics using a service account.

I need to bypass manual authorisation in a browser, so I have used a service account for which I have all the details, private_key, client_id, etc

https://www.googleapis.com/oauth2/v4/token&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion={PRIVATEKEY}

If I do the above, I receive not found.

Can anyone help?

Cheers

1
Getting access using a service account manually isn't easy here is some documentation. developers.google.com/identity/protocols/OAuth2ServiceAccount I would recommend you grab a Google client library and pick apart its code. - DaImTo

1 Answers

0
votes

The Server Side Authorization Embed API demo has an example of doing this. The example uses the Google APIs client library for Python, but, as @DalmTo mentions in their comment, you could look at what it's doing under the hood to replicate the requests.

Here's what the code that gets the access token looks like:

import json
from oauth2client.client import SignedJwtAssertionCredentials

# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'

# Load the key file's private data.
with open(KEY_FILEPATH) as key_file:
  _key_data = json.load(key_file)

# Construct a credentials objects from the key data and OAuth2 scope.
_credentials = SignedJwtAssertionCredentials(
    _key_data['client_email'], _key_data['private_key'], SCOPE)

# Defines a method to get an access token from the credentials object.
# The access token is automatically refreshed if it has expired.
def get_access_token():
  return _credentials.get_access_token().access_token