OAuth : Script to Automate Token Request

Ram117
Kilo Sage

Experts,

I am working on an integration between servicenow and another case management application. I am setting up OAuth integration. I am successful in setting up with  Grant type as JWT Bearer token. Now I need to do it with Grant type as password.

I did the initial OAuth Configurations in servicenow and is successful in setting up the REST message which successfully gives me Access Code.

I am having trouble in Automating this via script. 

 

 var payload = {

    "grant_type": gs.getProperty('x_1234_sf.sdc_oauth_grant_type').toString(),
    "username": gs.getProperty('x_1234_sf.sdc_oauth_user').toString(),
    "password": gs.getProperty('x_1234_sf.sdc_oauth_user_pwd').toString(),
    "client_id": gs.getProperty('x_1234_sf.sdc_client_id').toString(),
    "client_secret": gs.getProperty('x_1234_sf.sdc_client_secret').toString()

};

 

Need to pass this payload into the rest message

try {

	var r = new sn_ws.RESTMessageV2();
	r.setHttpMethod("POST");
	r.setEndpoint(gs.getProperty('x_1234_sf.sdc_oauth_end_point'));
	r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	r.setRequestBody(< how do I formulate the request body ?? >);


	this.response = r.executeAsync();
	this.response.waitForResponse(5);
	this.httpResponseStatus = this.response.getStatusCode();
	this.responseBody = this.response.getBody();
	var obj = JSON.parse(this.responseBody);

	this.result = {

	"resp_code": this.httpResponseStatus,
	"a_token": obj['access_token'],
	"type_token": obj['token_type']

	};

 

Please provide some guidance.

 

thx

ram.

1 ACCEPTED SOLUTION

Thank you for the reply Ankur.

Figured out the fix for this issue. 

What I was doing wrong is formulating the request Body while calling the OAuth API end point.

For Resource credentials grant type, the request body should be like as in the below script.

I do not have to use any of the GlideOAuth related methods.

var req = new sn_ws.RESTMessageV2();
req.setEndPoint( < OAUTh end point URL >);
req.setHttpMethod('POST');
req.setRequestHeader('content-type','application/x-www-form-urlencoded') 
req.setRequestBody(grant_type=" + grant_type + "&username=" + username + "&password="+encodeURI(pwd)+ "&client_id="+client_id+"+ "&client_secret="+client_secret));
var response = req.ExecuteAsync();
response.WaitForResponse(10);
var responseBody = response.getBody();
var obj = JSON.parse(responseBody);
gs.info('Token : "+obj.access_token);

 

With the above script, I am able to get the access code without converting the biz rule to Async & display the info message to the end user.

 

thx

ram.

View solution in original post

14 REPLIES 14

Robert Beeman
Kilo Sage

If you are trying to obtain an Access Token from a "Password" grant type, and you have your OAuth Provider record configured in the Application Registry (which will contain your Client ID and Client Secret), then you can obtain it with code like this:

var oAuthClient = new sn_auth.GlideOAuthClient(),
    username = gs.getProperty('your_username_sys_prop'),
    password = gs.getProperty('your_password_sys_prop'),
    params = {
      grant_type: "password",
      username: username,
      password: password
    };

var text = JSON.stringify(params),
    tokenResponse = oAuthClient.requestToken('name_of_oauth_provider', text),
    body = JSON.parse(tokenResponse.getBody()),
    token = tokenResponse.getToken(),
    accessToken = token.getAccessToken();

Thank you for the reply Robert, 

I tried looking at the UI action (get Auth Token) and built the below code & it is giving me the access code while running it from Scripts - Background. 

var requestor = '8fa624cfdb31dc101a929fc1ca96190e'; // sys id of the REST message
var requestor_context = 'sys_rest_message';
var oauth_provider_profile = 'd395a88fdb31dc101a929fc1ca961996'; // sys id of the OAuth Entity Profile
var oauth_provider_id = 'fb55a88fdb31dc101a929fc1ca961983'; // sys id of the OAuth Application Registry
var username = gs.getProperty('x_1234_sf.sdc_jwt_sub_parm');
var password = gs.getProperty('x_1234_sf.sdc_oauth_user_pwd');

var tokenRequest = new sn_auth.GlideOAuthClientRequest();
tokenRequest.setUserName(username);
tokenRequest.setPassword(password);

tokenRequest.setParameter('oauth_requestor_context', requestor_context);
tokenRequest.setParameter('oauth_requestor', requestor);
tokenRequest.setParameter('oauth_provider_profile', oauth_provider_profile); //set OAuth Entity Profile		
tokenRequest.setParameter('oauth_provider_id', oauth_provider_id);

var oAuthClient = new sn_auth.GlideOAuthClient();
var tokenResponse = oAuthClient.requestTokenByRequest(null, tokenRequest);
var errorMsg = tokenResponse.getErrorMessage();

gs.info('Response code: ' + tokenResponse.getResponseCode() + '\nErrorMessage: ' + errorMsg + '\n tokenResponse : '+tokenResponse);

if (tokenResponse) {
    var token = tokenResponse.getToken();    
    gs.info(token.getAccessToken());
    var oAuthToken = new sn_auth.GlideOAuthToken();
    gs.info(token.getAccessToken())
}

 

When I use this script in my custom logic ( from Incident -- > UI Action triggers the call to 3rd party), I get below 

 

find_real_file.png

 

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Ram,

you have configured the OAuth in order to get the access token from 3rd party endpoint

You have the rest message configured

You can get the OAuth token first and then use that in script of RestMessage

Regards
Ankur

 

 

 

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi Ankur,

I have done all the above. I am able to get the Access Code if I run it from background script

var requestor = '8fa624cfdb31dc101a929fc1ca96190e'; // sys id of the REST message
var requestor_context = 'sys_rest_message';
var oauth_provider_profile = 'd395a88fdb31dc101a929fc1ca961996'; // sys id of the OAuth Entity Profile
var oauth_provider_id = 'fb55a88fdb31dc101a929fc1ca961983'; // sys id of the OAuth Application Registry
var username = gs.getProperty('x_1234_sf.sdc_jwt_sub_parm');
var password = gs.getProperty('x_1234_sf.sdc_oauth_user_pwd');

var tokenRequest = new sn_auth.GlideOAuthClientRequest();
tokenRequest.setUserName(username);
tokenRequest.setPassword(password);

tokenRequest.setParameter('oauth_requestor_context', requestor_context);
tokenRequest.setParameter('oauth_requestor', requestor);
tokenRequest.setParameter('oauth_provider_profile', oauth_provider_profile); //set OAuth Entity Profile		
tokenRequest.setParameter('oauth_provider_id', oauth_provider_id);

var oAuthClient = new sn_auth.GlideOAuthClient();
var tokenResponse = oAuthClient.requestTokenByRequest(null, tokenRequest);
var errorMsg = tokenResponse.getErrorMessage();

gs.info('Response code: ' + tokenResponse.getResponseCode() + '\nErrorMessage: ' + errorMsg + '\n tokenResponse : '+tokenResponse);

if (tokenResponse) {
    var token = tokenResponse.getToken();    
    gs.info(token.getAccessToken());
    var oAuthToken = new sn_auth.GlideOAuthToken();
    gs.info(token.getAccessToken())
}

 

For some reason, i get TokenResponse as null when I trigger it from incidents.