How to get a token and refresh it in GSuite Integration through script

anushad
Tera Expert

Hi,

Can someone help me with GSuite integration process as I am struck on how to get and refresh token through script.

My requirement is to integrate GSuite with servicenow so whenever a new employee is hired a business should be triggered to create Gmail a/c for him.

To fulfill integration I have created OAuth Registry and REST Messages and tested them out by clicking on Get OAuth Token UI action and REST Message gave desired results. (Not through script)

I wrote a business rule to achieve this through script , but I wasn't able to succeed in getting or refreshing the token.

Can someone please let me know how to get/retrieve OAUth token 


var jsonStr2='{ "name": { "familyName":"' + gr.last_name + '" , "givenName":"'+ gr.first_name +'" },"password":"Password123!","primaryEmail":"'+gr.email +'"}';

gs.info("------ str s "+jsonStr2);


//var r = new sn_ws.RESTMessageV2();
if(rec.getDisplayValue('company') == 'ABC'){
gs.info('In the if condition');

var tokenRequest =new sn_auth.GlideOAuthRequestClient();
gs.info(tokenRequest);

// I am not sure what grantType to use here to retrieve the token.
tokenRequest.setGrantType("password");
tokenRequest.setUserName("abc@avc.com");
tokenRequest.setPassword("ABCDDJDDJ");
tokenRequest.setScope(null);
var oAuthClient = new sn_auth.GlideOAuthClient();
var tokenResponse = oAuthClient.requestToken('GSuite',tokenRequest);
var token = tokenResponse.getToken();
if(token){
gs.info("AccessToken:"+ token.getAccessToken());
gs.info("AccessTokenExpiresIn:"+ token.getExpiresIn());
gs.info("RefreshToken:"+ token.getRefreshToken());

}

// REST message script seem to execute without errors if the get the token using UI action(Get OAuth TOken) from REST Message form.


var r = new sn_ws.RESTMessageV2(' Rest Message', 'NewUser');

//r.setEndpoint("https://www.googleapis.com/admin/directory/v1/users");
//r.setRequestHeader("Authorization","oauth2" );
r.setAuthenticationProfile("oauth2","58cf67f4db7def001b96d2984b96193b");
r.setRequestHeader("Accept","application/json");
r.setRequestHeader("Content-Type","application/json");
r.setRequestBody(jsonStr2);
r.setHttpMethod("post");

var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();

gs.info("---Response is "+responseBody);

if(httpStatus == 200)
gs.addInfoMessage("An Email has been created.");
}



 

 

5 REPLIES 5

Aman Gulati
Giga Guru

@anushad @Ratnesh 

 

Were you able to generate the tokens programatically?

 Thanks

Aman