Generate a Google access token from a JSON service account file

Overview

  • Some Google components, all tGoogleDriveXX prior to Talend 7.x, take an access token directly as input. It can be generated either from OAuth credentials through the refresh token or from a service account JSON file.

  • An access token can also be used to call Google APIs directly using tHttpRequest or tRest components.

This article explains how to generate an access token from a service account JSON file.

 

Prerequisites

  1. Create a project in Google Cloud Platform.

  2. Activate the API you want to query.

  3. Create a Google Service Account and download the JSON key.

 

Procedure

  1. Create a Java routine called GoogleAuthUtils, and add the following code:

    package routines;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.util.Collections;
    
    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.services.drive.DriveScopes;
    
    public class GoogleAuthUtils {
    
        public static String getGoogleAccessToken(String jsonKeyFilePath)
                throws FileNotFoundException, IOException, GeneralSecurityException {
     
            GoogleCredential credential = GoogleCredential.fromStream(
                    new FileInputStream(jsonKeyFilePath)).createScoped(
                    Collections.singleton(DriveScopes.DRIVE));
     
            credential.refreshToken();
     
            return credential.getAccessToken();
        }	
    }
    
  2. Edit Routine Libraries, and add the following JAR files:

    google-api-client-1.19.0.jar
    jackson-core-2.x.x.jar
    google-oauth-client-1.19.0.jar
    google-http-client-jackson2-1.19.0.jar
    google-http-client-1.19.0.jar
    google-api-services-drive-v3-rev122-1.23.0.jar

    Configure the last library, google-api-services-drive-v3-rev122-1.23.0.jar, to the scope and service you want to query. You can find all available service libraries on the Maven Repository web site.

     

  3. Use a tJava component to call the routine and get the AccessToken.

    String googleAccessToken = GoogleAuthUtils.getGoogleAccessToken(
    "/Users/tdupoiron/talend/temp/projecttalend-9dc253bf2feb.json"
    );
    
    globalMap.put("GoogleAccessToken", googleAccessToken);

    The routine takes the absolute path of the service account JSON key as a parameter. The access token is then put into a global variable and can be used in components.

For more information on how to generate an access token from a service account JSON file, see the Google Using OAuth 2.0 for Server to Server Applications documentation page.

Version history
Revision #:
7 of 7
Last update:
‎04-14-2019 02:17 PM
Updated by: