Auto Generate Access token for Oauth 2 Outbound Rest Message third party integration
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-07-2023 01:01 AM
I want to connect ServiceNow with third party integration through Api, but my access token expires every time. So, I want to auto generate the access token every time its expired. For that need Script code, how to generate it automatically.
I Tried some code but getting the error, "Bearer token is missing in the HTTP request authorization header".
I tried some codes but it's not working for me can you help me with the script code for this issue.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-10-2023 12:56 AM
Hi @Divya2411 ,
You can use the following script code:
var client_id = '<your_client_id>';
var client_secret = '<your_client_secret>';
var grant_type = 'client_credentials';
var token_endpoint = '<your_token_endpoint>';
var token_grant_url = token_endpoint + "?grant_type=" + grant_type + "&client_id=" + client_id + "&client_secret=" + client_secret;
var token_request = new sn_ws.RESTMessageV2();
token_request.setEndpoint(token_grant_url);
token_request.setHttpMethod("post");
var token_response = token_request.execute();
var response_body = token_response.getBody();
var response_obj = JSON.parse(response_body);
var access_token = response_obj.access_token;
// Use the access token to make API calls
var api_request = new sn_ws.RESTMessageV2();
api_request.setEndpoint('<your_api_endpoint>');
api_request.setHttpMethod('get');
api_request.setRequestHeader('Authorization', 'Bearer ' + access_token);
var api_response = api_request.execute();
var api_response_body = api_response.getBody();
you need to replace the values of client_id, client_secret, grant_type, token_endpoint, and api_endpoint with the appropriate values for your integration. The token_grant_url variable constructs the URL to request a new access token using the client credentials grant type. The token_request object sends the request to the token endpoint, and the response is parsed to extract the access token.
If my response was helpful in resolving the issue, please consider accepting it as a solution by clicking on the ✅Accept solution button and giving it a thumbs up 👍. This will benefit others who may have a similar question in the future.
Thank you!
Ratnakar
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-11-2023 11:28 PM