Outbound REST web service call using oAuth
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-27-2017 10:52 AM
Hi community,
I need to create a ticket in Salesforce using REST which works fine. The problem is around the authentication method which is oAuth.
Here's the scenario that works:
1. Navigate to System Web Services -> Outbound -> REST Message
2. Select POST from HTTP Methods
3. Select UI Action "Get OAuth Token"
4. Enter username and password provider from 3rd party vendor (this gives me an access token)
OAuth Access token is available but will expire soon at 2017-06-27 14:16:43. Verify the OAuth configuration and click the 'Get OAuth Token' link below to request a new token.
5. From a Purchase Order, the following BR creates a ticket in Salesforce on PO creation:
When to run: ASYNC
(function executeRule(current, previous /*null when async*/) {
//First we need to retrieve RITM information to pass to 3rd party vendor
var req = new GlideRecord('sc_request');
if (req.get(current.init_request)) {
var ritm = new GlideRecord('sc_req_item');
ritm.addQuery('request', req.sys_id);
ritm.query();
if (ritm.next()) {
//retrieve the variables of the ritm
var store = ritm.u_requested_for.getDisplayValue();
var qty = ritm.quantity;
var emp = ritm.u_employee_name;
var oAuthClient = new sn_auth.GlideOAuthClient();
var params = {
grant_type:"password",
username:'xxxxxxxxxxxxxxxxxxxxxxx',
password:'xxxxxxxxxxxxxxxxxxxxxxxx'
};
//var json = new global.JSON();
var text = JSON.stringify(params);
var tokenResponse = oAuthClient.requestToken('3rd party vendor', text);
var token = tokenResponse.getToken();
var accessToken = token.getAccessToken();
var r = new sn_ws.RESTMessageV2('3rd party vendor', 'post');
r.setRequestHeader('Content-Type','application/json');
r.setRequestHeader('Authorization', 'Bearer ' + accessToken);
var aRequest = {
SiteId: "a08P0000002vylpIAA",
PO: 'Test from ServiceNow QA instance',
'Comment': "Created from SN QA for store: " + store + " quantity of " + qty,
OrderItems: [
{
'ItemId': "a1LP0000000mSmL",
Quantity: 2
},
{
'ItemId': "a1LP0000000mSmL",
Quantity: 2
}
]
};
r.setRequestBody(JSON.stringify(aRequest));
r.setStringParameter("short_description", current.short_description);
r.setAuthentication('oauth2', 'AirLiquide');
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
var responseObj = JSON.parse(responseBody);
//Create entry in External Ticket Match table
createTicketMatchEntry(responseObj.toString(), current.number);
//Update the external reference number
current.u_external_number = responseObj.toString();
current.update();
}
}
function createTicketMatchEntry(externalNum, num) {
var ext = new GlideRecord('u_integration_ticket_match');
ext.initialize();
ext.u_external_vendor = '3rd party vendor';
ext.u_external_number = externalNum;
ext.u_servicenow_ticket_number = num;
ext.u_servicenow_application = 'Purchase Order';
ext.insert();
}
})(current, previous);
Here's the scenario that DOESN'T work:
Skip steps from 1 to 4, which is to get the access token from the REST message and retrieve it using the BR only fails.
So basically, if I do not do steps 1 to 4, I am unable to authenticate to salesforce eventhough I am retrieving a valid access token using my BR.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-20-2018 09:36 AM
Your OAuth script was missing linking "OAuth requester profile" while getting OAuth token and linking that to REST message while executing REST api call. Please find below sample script which works for making a outbound REST OAuth call from one ServiceNow instance to another..
var oAuthClient = new sn_auth.GlideOAuthClient();
var requestor_context = 'test';
var requestor_id = 'abc@xyz.com';
var oauth_profile_id = '<sys_id_of_oauth_profile';
var params = {grant_type:"password", username:'admin', password:'password', oauth_requestor_context:requestor_context, oauth_requestor:requestor_id, oauth_provider_profile:oauth_profile_id};
var json = new global.JSON();
var text = json.encode(params);
var tokenResponse = oAuthClient.requestToken('<oauth_profile_name>', text);
var token = tokenResponse.getToken();
var access_token = token.getAccessToken() ;
gs.log("AccessToken:" + access_token);
gs.log("AccessTokenExpiresIn:" + token.getExpiresIn());
gs.log(" RefreshToken:" + token.getRefreshToken());
var r = new sn_ws.RESTMessageV2('<name_of_outbound_rest_message', 'Default GET');
//setting oauth profile and oauth requester profile
r.setAuthenticationProfile('oauth2', oauth_profile_id);
r.setRequestorProfile(requestor_context, requestor_id);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(responseBody);
