Comment
tharun_kumar_m
Mega Guru

Hi Rohit,

 

Nice article, it is really helpful. 

 

I was able to do the same using the resource owner password credentials grant workflow as mentioned below.

 

var requestBody;
var response;
var responseBody;
var status;

//var sys_id ='sys_id_of_incident;
try {
            var s = new sn_ws.SOAPMessageV2('Incident','get'); //(SOAP messgage name, SOAP function name)

//Generating O Auth access token via script - OAuth Registry definition//
            var oAuthClient = new GlideOAuthClient();
            var params ={grant_type:"password", username:"test", password:'password123'};   //source instance username and password with user having roles "SOAP" and "ITIL".
             var json =new JSON();
             var text = json.encode(params);
             var tokenResponse = oAuthClient.requestToken('Target SOAP', text); //Target instance Oauth Entity name
             var token = tokenResponse.getToken();
             var access_token = token.getAccessToken();
             var token = "Bearer "+ access_token.toString();
             s.setRequestHeader("Authorization", token); // Using the token information //
             //s.setRequestHeader("Content-Type", "text/xml");
             //s.setStringParameterNoEscape('sys_id', sys_id);


             s.setRequestBody('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:inc="http://www.service-now.com/incident"><soapenv:Header/><soapenv:Body><inc:get><sys_id>{enter_incident_sysid_here}</sys_id></inc:get></soapenv:Body></soapenv:Envelope>');


            response = s.execute();
            responseBody = response.getBody();
            status = response.getStatusCode();
            requestBody = s.getRequestBody();

             var xmldoc = new XMLDocument(responseBody.toString(), true);
             var number =xmldoc.getNodeText('//number');
             }
catch (ex) {
            var message = ex.message;
}
gs.info("Request Body: " + requestBody);
gs.info("Response: " + responseBody);
gs.info("HTTP Status: " + status);
gs.info("Number: " + number);

 

 

However, using the client credentials flow as described in your code throws me an error OAuthProblemException{error='server_error', description='access_denied', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}

Could you please let me know the values which I should fill for the below fields?

oauth_requestor_context
oauth_requestor
oauth_provider_profile

I don't see a method defined in ServiceNow docs using the parameters mentioned in your code.

https://docs.servicenow.com/bundle/washingtondc-api-reference/page/app-store/dev_portal/API_referenc...

 

Also, I cannot see the values in my requestBody when I pass the arguments using the setStringParameter() method. So I have used setRequestBody() method to perform the same actions.

 

Regards,

Tharun Kumar