OAuth 2.0 for Google Analytics

Abhiruchi Chaudhari
4 min readApr 18, 2023

--

OAuth 2.0 can be used to authorize a third-party application to access a user’s Google Analytics data

    +-----------------+                                         +-------------------------------------+
| Third-Party | | Google Authorization Server |
| Application | | |
+-----------------+ +-------------------------------------+
| |
| |
| |
| 1. Redirect user to authorization server with |
| client ID, redirect URI and scope |
|----------------------------------------------------------->|
| |
| |
| 2. Prompt user to authenticate and grant access |
|<-----------------------------------------------------------|
| |
| |
| 3. Redirect user back to redirect URI with |
| authorization code |
|<-----------------------------------------------------------|
| |
| |
| 4. Exchange authorization code for access token |
| using client ID and client secret |
|---------------------------------------------------------------->|
| |
| |
| 5. Respond with access token |
|<----------------------------------------------------------------|
| |
| |
| 6. Access Google Analytics API using access token |
|---------------------------------------------------------------->|
| |
| |
| 7. Respond with requested data |
|<----------------------------------------------------------------|
| |


OAuth 2.0 flow for Google Analytics

Steps :

  1. Register your application with the Google API Console and enable the Google Analytics API.
  2. Get the client ID and client secret for your application.
  3. Get google authorization code to access the user’s Google Analytics data.
  4. Authenticate and grant authorization to your application.
  5. Get the access token to your application from the authorization server.
  6. Access the user’s Google Analytics data using the access token.

Register your application with the Google API Console and enable the Google Analytics API

  • Go to Google API Console
  • Create a new project
  • Go to library section , search for “Google Analytics API” and enable it for your project

Get the client ID and client secret for your application

  • In the credentials section , Create credentials -> OAuth client ID -> Configure consent screen -> select user type as external or internal as per your need (external preferred) -> enter details and contact info -> add or remove scopes -> select all the scopes mentioned below ( you can filter according to your need)
  • add users ( can add your mail id as well)
  • Head back to credentials section as credentials are not yet generated , select web application , give a name , add a redirect uri as “http://localhost” (can add more than one uri)
  • Voila! OAuth client is created and you can store Client ID and Client Secret to use it later for obtaining tokens.

Get google authorization code to access the user’s Google Analytics data

  • Paste this url in the browser with your client-id
https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/analytics.readonly&access_type=offline&redirect_uri=http://localhost&response_type=code&client_id=<client-id>
  • You will get a response of following type with the code = 4%2F0AEtk6oCl6QWsPK54QDTdQ7THDVCS-GPIAIchPqoUnMv5zTxgdwGVG952VX7-j8GWYA
http://localhost/?code=4%2F0AEtk6oCl6QWsPK54QDTdQ7THDVCS-GPIAIchPqoUnMv5zTxgdwGVG952VX7-j8GWYA&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly

Authenticate and grant authorization to your application.

  • The user is prompted to authenticate with their Google account if they are not already signed in.
  • The user is presented with a consent screen that describes the authorization request, and asked to grant or deny authorization to your application.
  • If the user grants authorization, they are redirected back to your application with an authorization code

Get the access token to your application from the authorization server

  • Curl request to get access token and refresh token
curl --location --request POST 'https://accounts.google.com/o/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: NID=511=HCXdiRL_N5rs_0CoPr0Kq4jJJ4mAwlq21B51AWiv3CpQeloWLV9WKbjoLLnvLfXiwJW-Rn7sGqpp_ECqiisp4dYefNJeh4Pa4qLGZLW0vP_jcNIyr-GP6bdD8oQJ5re4PTcVgNU3UjoiiC5Q_tWfscFNZWXZJRYcVzqA3u2l1A0; __Host-GAPS=1:6dbX2JhkxvNv80uqAtMS_Fpu3H-bVg:LMzll62vE1DyrvS_' \
--data-urlencode 'code=<authorization-code>' \
--data-urlencode 'client_id=<client-id>' \
--data-urlencode 'client_secret=<client-secret>' \
--data-urlencode 'redirect_uri=http://localhost' \
--data-urlencode 'grant_type=authorization_code'

Response type is as follows

{
"access_token": "ya29.a0AexVLshlw4_H35o73bSSNQ8YIYzUsKEgYzVx8Mq1fhpk_-t8P73RHwPNGV3J5HuEejggesK_T11tO6BCEdJH2oRdaTQaCgYKAc8SARMSFQF4udJhCuXardhyQ7kDYmmdWNSM4A0165",
"expires_in": 3567,
"scope": "https://www.googleapis.com/auth/analytics.readonly",
"token_type": "Bearer"
}

Access the user’s Google Analytics data using the access token

  • Include the access token in the Authorization header of API requests to the Google Analytics API, using the format “Bearer ACCESS_TOKEN”.
  • The API responds with the requested data
  1. Get metadata
curl --location --request GET 'https://analyticsdata.googleapis.com/v1beta/properties/336644331/metadata' \
--header 'Authorization: Bearer <access-token>'

2. Get account summaries

curl --location --request GET 'https://www.googleapis.com/analytics/v3/management/accountSummaries' \
--header 'Authorization: Bearer <access-token>'

3. Get all accounts to which the user has access

curl --location --request GET 'https://www.googleapis.com/analytics/v3/management/accounts' \
--header 'Authorization: Bearer <access-token>'

You can view & fork my Postman collection uploaded here:

Troubleshooting (FGE )

Redirect uri mismatch : Verify if redirect uri mentioned in the curl request and added in the application (step 2) is same.

“error”: “invalid_grant”, “error_description”: “Malformed auth code.” : Regenerate authorization code (step 3) and try curl request again (step 4) .

Still getting the error? Retry in a new postman session.

Refresh token not generated as a response for step 5 : Refresh token will be generated only once on first authorization from the user.Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return the refresh token.

Hack : Go to the page showing Apps with access to your account — https://myaccount.google.com/u/0/permissions. Under the Third-party apps menu, choose your app.Click Remove access and then click Ok to confirm.The next OAuth2 request you make will return a refresh token

--

--