Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Outbound REST web service call using oAuth

maxcarrier
Kilo Explorer

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.

10 REPLIES 10

Hi Maxime,



So in Postman tool it is working fine.


1) Getting the access token


2) Using this access token in actual API call



Can you check what url you are using for getting the access token. Also can you try sending those 2 parameters along with sending grant_type, username, password



  • Client ID = Consumer Key from Salesforce
  • Client Secret = Consumer Secret from Salesforce


As far as I know you need to send client_id and client_secret while getting access token when grant_type is password:



Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact.


Thanks


Ankur


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

Hi Maxime,



Any update on this?


Can you mark my answer as correct, helpful and hit like if you were able to achieve the requirement. This helps in removing this question from unanswered list and helps users to learn from your thread. Thanks in advance.



Regards


Ankur


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

Hi Maxime,



Any update on this?


Can you mark my answer as correct, helpful and hit like if you were able to achieve the requirement. This helps in removing this question from unanswered list and helps users to learn from your thread. Thanks in advance.



Regards


Ankur


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

Hi Maxime,



This links should help you:



How to Connect to Salesforce REST API with OAut... | Dell Boomi Community


Access to REST API SALESFORCE using username and password? - Salesforce Developer Community


Salesforce Developers


How to Setup OAuth2 authentication for outbound RESTMessageV2 integrations


How to make a integration between Salesforce and ServiceNow Using APEX - Calling Rest API from SN? -...




Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact.


Thanks


Ankur


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

Hi Maxime



I am getting the same error, were you able to resolve this issue?



Error:


com.glide.communications.ProcessingException: User Not Authenticated. OAuth token has expired or has not been retrieved.