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

InfoTrust Becomes Official Google Cloud Partner

InfoTrust Becomes Official Google Cloud Partner

For years, the experienced cloud engineering team at InfoTrust has helped major multi-brand clients across the globe drive their business objectives forward. With a…

Deloitte Recognizes InfoTrust in Annual Technology Fast 500 Ranking

Deloitte Recognizes InfoTrust in Annual Technology Fast 500 Ranking

Last week, Deloitte honored the experienced digital analytics consulting, data governance, and technology team at InfoTrust among the 500 fast-growing North American companies in…

The Most Useful Google Analytics Reports and Dashboards for Black Friday

The Most Useful Google Analytics Reports and Dashboards for Black Friday

With the holiday season rapidly approaching, Black Friday weekend is just around the corner. Recently, we asked if your digital analytics team is ready…

Migrating Tag Inspector from Python 2 to Python 3

Migrating Tag Inspector from Python 2 to Python 3

Recently, our engineering team completed a migration of our proprietary tag auditing and management platform from Python 2 to Python 3. This upgrade brings…

Get to Know All the Products in the Google Marketing Platform

Get to Know All the Products in the Google Marketing Platform

While most organizations are aware of the Google marketing stack, many only utilize one or two of its products. While using a single Google…

In-Housing in Your Organization’s Future? Start with This Conversation

In-Housing in Your Organization’s Future? Start with This Conversation

It’s time to have a real conversation about your company’s internal structure and capabilities. Are you being asked by management to make in-housing a…

Tag Inspector’s Cookie Detection Feature Receives Quanties Award for Best New Technology

Tag Inspector’s Cookie Detection Feature Receives Quanties Award for Best New Technology

At the Digital Analytics Association’s OneConference event last evening in Chicago, Tag Inspector’s new cookie detection feature received the Quanties Award for Best New…

Lead Analytics Consultant Mai AlOwaish Honored with DAA President’s Award

Lead Analytics Consultant Mai AlOwaish Honored with DAA President’s Award

At InfoTrust, our team works not only to grow our business and community, but also to further the digital analytics industry as a whole….

Join InfoTrust on the Journey Towards Organizational Maturity in Supporting Equality in Tech

Join InfoTrust on the Journey Towards Organizational Maturity in Supporting Equality in Tech

One of the pivotal moments of my career as an entrepreneur was hearing Jeff Hoffman share his legacy as a founder of Priceline.com, uBid.com,…

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.