Google Analytics Authentication OAuth 2.0 (step by step)

Since 20 April 2015 google has shutdown ClientLogin, AuthSub, OAuth 1.0 (see detail). I don’t know exactly when the services are finally shut down, I have a portal which uses Google Analytics to retrieve web visitor. Error console log in Eclipse is like this :

AnalyticsService analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0"));
		analyticsService.setUserCredentials(username, password);
Could see the following com.google.gdata.util.AuthenticationException: Error authenticating (check service name) in logs

at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:688)
	at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
	at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
	at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
	at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
	at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)

Okay, so we should change authentication using OAuth 2.0. There are several things that you should remember before migrate to OAuth 2.0.

1. Download Google Analytics Java Client version 3 from here

2. Create a New Project in Google Developers Console

Create a New Project Google Developers

Create a New Project Google Developers

 

If you don’t have a project, you can create a new project by clicked Create Project button and put the Project Name. Click the project name (API Project in this sample) to enable Google API Services.

3. Enable Google API Services

Go to APIs & auth -> APIs to choose which services you would like to enable

Enable Google API Service

Enable Google API Service

 

4. Enable Google OAuth Credentials

Go to APIs & auth -> Credentials and create new Service Account by clicked Create new Client ID button and choose Service Account for Application Type and choose P12 Key for Key Type.  It will generate P12 file token and you must download it, P12 key will be used to pairing authentication in Google Client-side application.

P12 Key

P12 Key

Once you have added Service Account you will have some information regarding these Service. There is some information that you should remember and very important.

Client ID OAuth

Client ID OAuth

5. Register Email Address to Google Analytics

Sign in to your Google Analytics account and go to Admin -> User Management to register the email address.

Register Email Address

Register Email Address

6. Getting Google Analytics Table ID

Go to Admin -> View tab -> View Settings to get Table ID information

Get Table ID Information

Get Table ID Information

7. Create a Simple Java Project as Google Client

Create a Simple Java Project then add several library, create a main class.

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.Analytics.Data.Ga.Get;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.GaData;

public class HellowAnalyticsV3Api {
	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
	private static final JsonFactory JSON_FACTORY = new JacksonFactory();

	public static void analyticsExample() throws GeneralSecurityException, IOException {
		// This is the .p12 file you got from the google api console by clicking generate new key
	    File analyticsKeyFile = new File("your p12 file path");

	    //checking file
	    if(analyticsKeyFile.exists()){
	    	System.out.println("file : "+analyticsKeyFile.getName()+" exist");
	    }else {
	    	System.out.println("file : "+analyticsKeyFile.getName()+" doesn't exist");
	    }

	    String apiEmail = "yourEmailAddressinServiceAccount@developer.gserviceaccount.com";
	    String clientId = "yourClientIdinServiceAccount.apps.googleusercontent.com";
	    String certFingers = "yourCertificateFingersinServiceAccount";
	    String tableId = "ga:yourViewIdinGoogleAnalyticsView";

	    Date now = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String startDate = "2010-08-01";
	    String mertrics = "ga:visits";
		String endDate = df.format(now);

	    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(apiEmail)
        .setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
        .setClientSecrets(clientId, certFingers)
        .setServiceAccountPrivateKeyFromP12File(analyticsKeyFile).build();

	    Analytics analyticsService = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName("Google Client OAuth 2.0")
        .build();

	    // Use the analytics object build a query
	    Get get = analyticsService.data().ga().get(tableId, startDate, endDate, mertrics);

	    // Run the query
	    GaData data = get.execute();

	    // Do something with the data
	    if (data.getRows() != null) {
	        for (List<String> row : data.getRows()) {
	            System.out.println("and the result of visitor is : "+row);
	        }
	    }
	}

	public static void main(String[]args){
		try {
			analyticsExample();
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

Okay, I hope this can help you .. and sorry for any grammatical error cause my English is not good hahahaha …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>