Share on facebook
Share on twitter
Share on linkedin
Share on email

Google Tag Manager and Google Analytics API Authorization

Google Authentication with API

Authorization is the first step of managing and accessing your account data through the Google APIs. There are a number of ways for your application to authenticate. For this example we will demonstrate how you can use the Java Client Library to access your GTM and GA accounts.

Official documentation can be found here.

Auth Types

Accessing the API requires some form of an authentication key. You can either use a service account key, for server to server interactions, or an oauth client ID to gain access for a specific user.

Service Account

A google service account is used as a way to provide access to your data to support server to server interactions. This is useful when you are creating a new application and setting up a tie-in to Google Tag Manager or Google Analytics. You will need grant access to this service account.

User Account

If your application needs to act as the user, OAuth will allow them to login using their Google credentials. Browser OAuth is where your application will open a web browser to login using their own Google account to grant access to Google Tag Manager or Google Analytics.

In the case that you need your application to act as a different user, another way we can authenticate is by having the user provide their JSON key along with an authorization token.

NOTE: This provides you complete access to act on behalf of the other user utilizing the API. This should be done VERY carefully and with caution. In most cases where you feel you should do this, you should first see if it’s possible to use a service account instead.

Setting Up a Project

The first step is getting your project setup. This section outlines creating the project and then creating an OAuth Client ID or Service Account Key for the project, based on your needs.

create-project1

create-project2

Create a project

library-menu

Enable Google Analytics and Tag Manager APIs in the Library Menu

1) Search for Tag Manager, Click Tag Manager API, Click Enable

2) Repeat for Analytics API

Create an OAuth Client ID or Service Account Key

OAuth Client ID

consent-screen

Configure Consent Screen

other

For using the Java SDK, we’ll select ‘Other’

It will then show you your client ID and client secret. You can ignore these because we’ll download the JSON file in a moment.

download

Click the download icon next to your client ID to download the json file. Put this file into the GoogleAPIAuthExample/authkeys folder.

Service Account Key

service-account-key-type

 

Be sure to Specify P12 Key Type

Download your p12 key into the GoogleAPIAuthExample/authkeys folder

Get your service account id from the Manage Service Accounts Page and take note of this for later.

Setup Options

  • DataStore Path: This is the folder where your authorized credentials will be stored. If this file is deleted it will require the user to reauthenticate.
  • Application Name: The name of your application.
  • P12_AUTH_KEY_FILEPATH or JSON_AUTH_KEY_FILEPATH is used to specify the relative location of your auth key.
  • SERVICE_ACCOUNT_EMAIL: If you are using a service account, this is the constant you need to specify the service account ID in. It should have similar suffix to “@iam.gserviceaccount.com”

Service Account Auth Usage


	private static Credential authorizeServiceAccount() throws Exception {
	    // Construct a GoogleCredential object with the service account email
	    // and p12 file downloaded from the developer console.
	    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
	    GoogleCredential credential = new GoogleCredential.Builder()
	        .setTransport(httpTransport)
	        .setJsonFactory(JSON_FACTORY)
	        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
	        .setServiceAccountPrivateKeyFromP12File(new File(P12_AUTH_KEY_FILEPATH))
	        .setServiceAccountScopes(AnalyticsScopes.all())
	        .build();
	    return credential;
	  }

Token + JSON Auth Usage


private static Credential authorizeWithAccessToken() throws FileNotFoundException, IOException  {
		// Load client secrets.
		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
				new InputStreamReader(new FileInputStream(JSON_AUTH_KEY_FILEPATH)));

		//Specify which scopes are enabled.
		List gaGTMScopes = new ArrayList();
		gaGTMScopes.addAll(AnalyticsScopes.all());
		gaGTMScopes.addAll(TagManagerScopes.all());

		// Set up authorization code flow for all auth scopes.
		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
				clientSecrets, gaGTMScopes).setDataStoreFactory(dataStoreFactory).setAccessType("offline")
						.build();

		StoredCredential scred = flow.getCredentialDataStore().get("user");
		if (scred != null) {
			GoogleCredential cred = new GoogleCredential.Builder().setTransport(httpTransport)
					.setJsonFactory(JSON_FACTORY).setClientSecrets(clientSecrets).build();

			return cred.setAccessToken(scred.getAccessToken()).setRefreshToken(scred.getRefreshToken());
		} else {
			String url = flow.newAuthorizationUrl().setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).build();

			Scanner reader = new Scanner(System.in); // Reading from System.in
			System.out.println(url);
			System.out.println("Enter access token: ");
			String accessToken = reader.next();
			reader.close();

			// Authorize.
			GoogleTokenResponse response = flow.newTokenRequest(accessToken)
					.setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).execute();
			return flow.createAndStoreCredential(response, "user");
		}
	}

Browser OAuth Usage


	private static Credential authorize() throws FileNotFoundException, IOException  {
		// Load client secrets.
		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
				new InputStreamReader(
						new FileInputStream(JSON_AUTH_KEY_FILEPATH)));
		// Set up authorization code flow for all auth scopes.
		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
				clientSecrets, AnalyticsScopes.all()).setDataStoreFactory(dataStoreFactory).build();
		// Authorize.
		return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
	}

Resources

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on email
Email

Other Articles You Will Enjoy

5 Ways Digital Analytics Can Help Retail and eCommerce Companies in Times of Crisis

5 Ways Digital Analytics Can Help Retail and eCommerce Companies in Times of Crisis

What an incredible amount of change in just a few weeks. By now, nearly every industry and working professional has felt the effects of…

Save 10+ Hours Per Week With These Marketing Analytics Tips

Save 10+ Hours Per Week With These Marketing Analytics Tips

With the widespread adoption of stay-at-home policies across the globe, many of us are juggling our professional and personal responsibilities while working from home….

How the COVID-19 Pandemic is Affecting CPG Search Trends

How the COVID-19 Pandemic is Affecting CPG Search Trends

As the world has come to what feels like a standstill due to the coronavirus (COVID-19) outbreak, many businesses are seeing below-average purchasing behaviors….

How to Create First-Party Audiences in Campaign Manager

How to Create First-Party Audiences in Campaign Manager

As technology evolves, conversations around first-party data are becoming more and more common. Soon buying customer data or using third-party data sources for advertising…

How to Combat Possible Adobe Analytics Data Loss

How to Combat Possible Adobe Analytics Data Loss

Early this morning, Adobe sent a letter to Adobe Analytics customers addressing “some gaps in your data between April 13 and April 16.” For…

Working Remote? Beware of Data Visualization Risks

Working Remote? Beware of Data Visualization Risks

I acknowledge that I’m walking a fine line here. On the one hand, I’m seeing so many businesses do what appears to be capitalizing…

5 Analytics Tactics the Travel and Hospitality Industries Can Implement in Challenging Times

5 Analytics Tactics the Travel and Hospitality Industries Can Implement in Challenging Times

In recent weeks, as health concerns are creating an impact on many aspects of our daily lives, a number of businesses and industries are…

Planning for a Post-COVID-19 World: The Fight For Consumer Habits

Planning for a Post-COVID-19 World: The Fight For Consumer Habits

I’ve been a loyal gym member for almost 10 years. When I’m not traveling, I’m in the gym 5-6 times a week. The facilities…

5 Analytics and Reporting Tactics for CPG Companies in Times of Crisis

5 Analytics and Reporting Tactics for CPG Companies in Times of Crisis

As we’ve seen over the last few weeks, when a major crisis occurs, it can have a significant negative impact on many industries. For…

Our website uses cookies and may collect user information to provide a good experience. Read our Privacy Policy here.

Leave Us A Review

Leave a review and let us know how we’re doing. Only actual clients, please.