Oauth 2.0 token request header parameters

Michael Hilton
Tera Contributor

I am trying to build a Oauth 2.0 credential but the token authorization requires that a resource parameter is defined for the token and sent in the body of the token request. I am not sure if/how this is possible with out just building a custom script. I was just building this using the Connections and Credentials.

1 REPLY 1

sumanta pal
Kilo Guru

Sure, you can create an OAuth 2.0 credential in ServiceNow by following these steps:

1. Navigate to System OAuth > Application Registry.
2. Click on New to create a new application registry.
3. Select "Create an OAuth API endpoint for external clients".
4. Fill in the required fields such as Name, Client ID, Client Secret, etc.
5. In the "Redirect URL" field, enter the URL where you want the authorization code to be sent.
6. Click on Submit to create the application registry.

Now, to send the resource parameter in the body of the token request, you would need to create a scripted REST API. Here's how you can do it:

1. Navigate to System Web Services > Scripted REST APIs.
2. Click on New to create a new scripted REST API.
3. Fill in the required fields such as Name, API ID, etc.
4. Click on Submit to create the scripted REST API.
5. Now, click on Resources related list and then click on New to create a new resource.
6. In the Script field, you can write a script to send the resource parameter in the body of the token request.

Here's a sample script:

javascript
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var requestBody = request.body.data;
var resource = requestBody.resource;

var httpClient = new sn_ws.RESTMessageV2();
httpClient.setHttpMethod('post');
httpClient.setEndpoint('https://your-oauth-server.com/token');
httpClient.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpClient.setRequestBody('grant_type=client_credentials&client_id=your-client-id&client_secret=your-client-secret&resource=' + resource);
var httpResponse = httpClient.execute();
var httpResponseStatus = httpResponse.getStatusCode();
var httpResponseContentType = httpResponse.getHeader('Content-Type');
var httpResponseObj = JSON.parse(httpResponse.getBody());

response.setStatus(httpResponseStatus);
response.setContentType(httpResponseContentType);
response.setBody(httpResponseObj);
})(request, response);


This script sends a POST request to the OAuth server with the resource parameter in the body of the request. The response from the OAuth server is then sent back in the response of the scripted REST API.

Please replace 'https://your-oauth-server.com/token', 'your-client-id', and 'your-client-secret' with your actual OAuth server URL, client ID, and client secret respectively.


nowKB.com