Google Tag Manager and Google Analytics API Authorization

Google Authentication with API
Estimated Reading Time: 5 minutes

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

Author

  • Seth Rujiraviriyapinyo

    Seth Rujiraviriyapinyo creates GTM implementations, automates changes using GA and GTM APIs, and supports multiple clients to implement analytics tracking across their sites. As an Analytics Engineer Seth specializes in using the GA and GTM APIs to master account management and standardization.

Facebook
Twitter
LinkedIn
Email
Originally Published: September 6, 2016

Subscribe To Our Newsletter

July 20, 2023
Originally published on September 6, 2016

Other Articles You Will Enjoy

Advanced Analysis Techniques in Google Analytics 4: How to Use AI-Powered Insights and Predictive Analytics for Effective Marketing

Advanced Analysis Techniques in Google Analytics 4: How to Use AI-Powered Insights and Predictive Analytics for Effective Marketing

AI-powered insights and predictive analytics are revolutionary tools reshaping the modern marketing landscape. These advanced analytics techniques, particularly prominent in Google Analytics 4 (GA4),…

8-minute read
Is It Time to Upgrade? 4 Signs Your Organization Needs Google Analytics 4 360

Is It Time to Upgrade? 4 Signs Your Organization Needs Google Analytics 4 360

As VP of Partnerships at InfoTrust, I’ve had the opportunity to talk with hundreds of decision-makers about their interest in upgrading to Google Analytics…

4-minute read
How Data Maturity Can Cultivate a Data-Driven Culture

How Data Maturity Can Cultivate a Data-Driven Culture

Data-driven decisions are a buzz topic in Martech. It is essential for C-suite executives to understand and more importantly, use their data to move…

4-minute read
Predictive Analytics in Google Analytics 4: How to Use Machine Learning to Forecast User Behavior and Outcomes

Predictive Analytics in Google Analytics 4: How to Use Machine Learning to Forecast User Behavior and Outcomes

Google Analytics 4 (GA4) is embracing the power of machine learning by incorporating predictive analytics within the platform so that you can use your…

7-minute read
Tracking User Behavior with Events in Google Analytics 4: Examples and Use Cases

Tracking User Behavior with Events in Google Analytics 4: Examples and Use Cases

So you’ve created your Google Analytics 4 (GA4) properties, created your data stream(s), and followed all the necessary steps to configure your property. Now…

5-minute read
How Does BigQuery Data Import for Google Analytics 4 Differ from Universal Analytics?

How Does BigQuery Data Import for Google Analytics 4 Differ from Universal Analytics?

All Google Analytics 4 (GA4) property owners can now enable ‌data export to BigQuery and start to utilize the raw event data collected on…

2-minute read
Google Analytics 4 Implementation Checklist: Ensure You’re Tracking Everything You Need

Google Analytics 4 Implementation Checklist: Ensure You’re Tracking Everything You Need

In the dynamic landscape of digital marketing, data is supreme. Understanding user behavior, preferences, and interactions on your website is crucial for making informed…

4-minute read
Google Tag Best Practices for Google Analytics 4

Google Tag Best Practices for Google Analytics 4

After collaborating with several of my colleagues at InfoTrust including Bryan Lamb, Head of Capabilities, Corey Chapman, Senior Tag Management Engineer, Chinonso Emma-Ebere, Tech…

4-minute read
Leveraging Attribution Models in Google Analytics 4 to Improve Your Marketing Strategy: Tips and Best Practices

Leveraging Attribution Models in Google Analytics 4 to Improve Your Marketing Strategy: Tips and Best Practices

In the dynamic landscape of digital marketing, understanding the customer journey is crucial for optimizing strategies and maximizing ROI. Google Analytics 4 (GA4) introduces…

5-minute read

Get Your Assessment

Thank you! We will be in touch with your results soon.
{{ field.placeholder }}
{{ option.name }}

Talk To Us

Talk To Us

Receive Book Updates

Fill out this form to receive email announcements about Crawl, Walk, Run: Advancing Analytics Maturity with Google Marketing Platform. This includes pre-sale dates, official publishing dates, and more.

Search InfoTrust

Leave Us A Review

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