Search code examples
oauthoauth-2.0google-oauthgoogle-analytics-api

Proper method of getting a server auth access token for a client to use with google analytics


I have a global account that has several views that I want to use on the server side to embed dashboards for the various views on the client side. From what I understand, I get an access token using a service account on the server side and can then send the access token to the client side whenever needed. I was wondering, is this the correct flow? Should the access token be per session?

The authorization on the client side shown here has a field for a server auth access token, but couldn't find documentation on the exact flow I wanted. Basically I'm unsure what the proper way of generating that server auth access token is. Any help/pointers would be very much appreciated.


Solution

  • [Here][1] is an example of how to set up server side auth. The above code creates a new token when anyone visits the site. You can see the endpoint that gets that access token [here][2].

    Below are the general steps to get to a working version:

    Step 1: Create a service account and download the JSON key

    Step 2: Add the service account as a user in Google Analytics

    Step 3: Use the JSON key data to request an access token

    # service-account.py
    
    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
    

    Back to the client side:

    Step 4: Load the Embed API library.

    <script>
    (function(w,d,s,g,js,fs){
      g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
      js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
      js.src='https://apis.google.com/js/platform.js';
      fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
    }(window,document,'script'));
    </script>
    

    Step 5: Add HTML containers to host the dashboard components.

    <div id="chart-1-container"></div>
    <div id="chart-2-container"></div>
    

    Step 6: Write the dashboard code.

    Use the access token obtained in step 3 to authorize the Embed API.

    gapi.analytics.ready(function() { /** * Authorize the user with an access token obtained server side. */ gapi.analytics.auth.authorize({ 'serverAuth': { 'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}' } }); ... The additional work of creating an endpoint which returns the token depends on your back end implementation but the source code of how the demo does it can be found [here][2]. [1]: https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/ [2]: https://github.com/googleanalytics/ga-dev-tools/blob/abb3c5a18160327a38bf5c7f07437dc402569cac/lib/controllers/server_side_auth.py