logo

NJP

OAuth 2.0 authentication for SOAP Outbound Request

Import · Sep 14, 2022 · article

Out of the Box ServiceNow offers us limited option of "Basic" authentication option to authenticate and send out Outbound Requests to Third Party Applications using the SOAP protocol.Nowadays the most common authentication and reliable method used to authenticate a web service is OAuth 2.0, and most customers has a requirement to use OAuth 2.0 authentication for SOAP based communications between the platforms.Recently I have come across such requirement and have solved the issue by using a server scripted Approach.Solution Overview : Used the SOAPMessageV2() function to trigger the SOAP function and since the TPA was accepting a bearer token in the Request Header was able to pass the OAuth Token via script.Used the OOB Oauth Token Registry configuration and used the Oauth entity profile to generate the Access token using the GlideOauthClient()

 try {
            var s = new sn_ws.SOAPMessageV2('APINAME', 'FUNCTION NAME');

            //Generating O Auth access token via script - OAuth Registry definition//
            var oAuthClient = new sn_auth.GlideOAuthClient();
            var requestor_context = 'test';
            var requestor_id = '[email protected]';
            var oauth_profile_id = 'SYS_ID'; // profile ID [sys_id of  'OAuth Entity Profiles' (oauth_entity_profile) record in OAUTH registry  record]

            var params = {
                grant_type: "client_credentials",
                username: 'ClientID',
                password: 'ClientSecret',
                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 Test', text); //'oAuth Test' is the name of the OAuth application registry record (oauth_entity)
            var token = tokenResponse.getToken();
            var access_token = token.getAccessToken();
        var token = "Bearer "+ access_token.toString();
            s.setRequestHeader("Authorization", token); // Using the token information //
            var response = s.execute();
            var responseBody = response.getBody();
            var status = response.getStatusCode();
        } catch (ex) {
            var message = ex.message;
        }

image

View original source

https://www.servicenow.com/community/developer-articles/oauth-2-0-authentication-for-soap-outbound-request/ta-p/2317592