How to get Access Token using JWT in Netsuite (Oauth 2 Integration)

In this post we will learn how to connect your NetSuite to Google APIs. In order to connect Netsuite to Google drive or Excel or any Google Application you need to first authenticate your app using Oauth 2.0 server to server communication.

To have server to server communication you need to create service account in Google Cloud console

Once you have created a service account you need to generate private keys

To do that just click on the email link

Once you have created the private keys now we can start coding

We will use a third party library to generate JWT

You can visit this page to download the library https://kjur.github.io/jsrsasign/

After downloading and extracting the zip file look for this file jsrsasign-all-min.js

Now we need to make some changes to this file to make it work with Netsuite

Add these three objects at the beginning of the file

var navigator={
    appName:"Microsoft Internet Explorer"
};
var window={};

var KJUR={};

Now upload this file in Netsuite file cabinet SuiteScript folder

In order to make this library work with Suitescript 2.0 we need to define NAMD confi

Create a config.json file and paste this

{
    "paths": {
        "rsasign": "SuiteScripts/jsrsasign-all-min.js"
    },
    "shim":{
        "rsasign": {
            "exports": "KJUR"
        }
    }
}

after creating this file put it in same suitescrpt folder of file cabinet

Now use the below code to generate JWT and Access Tokens

/**
* @NApiVersion 2.x
* @NScriptType UserEventScript
* @NAmdConfig  /SuiteScripts/config.json
*/

define(['N/https','rsasign'], function (https,rsasign) {

    function afterSubmit() {
            var privateKey ="-----BEGIN PRIVATE KEY-----Your Private Key here n-----END PRIVATE KEY-----n";            
            privateKey =privateKey.replace(/n/g,' ');

            const iss = "google-netsuite-service-accoun@avid-atlas-378794.iam.gserviceaccount.com"; // service account email
            const scope = "https://www.googleapis.com/auth/prediction";
            const aud = "https://oauth2.googleapis.com/token";
            const EXPIRATION = 60 * 60 // 1 hour

            // prepare claimset

            const claimSet ={
              "iss": iss,
              "scope": scope,
              "aud": aud,
              'exp': Math.round(new Date().getTime() / 1000) + EXPIRATION,
              "iat": Math.round(new Date().getTime() / 1000)
            };

            const header = KJUR.jws.JWS.readSafeJSONString(JSON.stringify({"alg":"RS256","typ":"JWT"}));

            // generate JSON web token

            const jwt = KJUR.jws.JWS.sign(null, header, JSON.stringify(claimSet), privateKey);

            log.debug({
                          title: 'jwt',
                          details: jwt
                        });

            // send jwt to receive access token

            const body ={
                'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                'assertion':jwt
            }

            const response = https.post({
                url: aud,
                body: JSON.stringify(body),
                headers: {'Content-Type': 'application/json'}                
            });


                        log.debug({
                         title: 'response',
                         details: response.body
                        });

            const accessToken = response.access_token;

    }

    return {
        afterSubmit: afterSubmit
        };

});

SuiteScript 2.0 code

Now deploy this code in Userevent after submit and it will generate Access tokens for you. Using that access tokens you can transfer data from Netsuite to Google APIs

When we edit and save a record this userevent script will trigger and it will give us access_token as shown in above logs