OAuth Generate new access token from business rule
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎12-06-2018 07:05 AM
Hi All
Need help very urgent
I am working on OAuth 2.0 integration from ServiceNow to the external system but I am not able to generate new access token from business rule once the access token is expired.
Step 1:- I have set up the OAuth for the third party with client Id and secret Id.
Step 2:- I have setup REST Message with this OAuth authentication and set up the post method.
on click of "Get OAuth Token" it generated the access token, on click of test it gave me the success response.
Step 3:- I have set up the business rule to call this REST Message to make a post request. this will give the success response if the access token is not expired, once the access token is expired the business rule will fail. so I have written the script to generate the access token in the business rule but it is not working, need help urgently.
below is the sample code
(function executeRule(current, previous /*null when async*/) {
try {
var oAuthClient = new GlideOAuthClient();
var params ={grant_type:"password", username:"admin@externalsystem.com", password:"pass@123"};
var json =new JSON();
var text = JSON.stringify(params);
var tokenResponse = oAuthClient.requestToken('XXXX default_profile', text);
var token = tokenResponse.getToken();
var accessToken = token.getAccessToken();
var RefreshToken = token.getRefreshToken();
var r = new sn_ws.RESTMessageV2('Case Create API', 'post');
r.setRequestHeader("Content-Type","application/json");
r.setRequestHeader("Authorization", "Bearer " + accessToken);
r.setAuthentication("oauth2", "XXXX default_profile");
r.setStringParameter("sysid",current.sys_id);
r.setStringParameter("number",current.number);
r.setStringParameter("description",current.description);
r.setStringParameter("priority",current.priority);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
}
catch(ex) {
var message = ex.message;
gs.print("ex==:" + ex);
}
})(current, previous);
- Labels:
-
Integrations
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎12-07-2018 08:49 AM
Code snippet to get a new Access Token when the previous Access token expires.
1. You need the Refresh toke to execute this code
2. You need the OAuth Applciation registry Name to get the new Access Token.
//GlideOAuthClientRequest
var clientRequest = new sn_auth.GlideOAuthClientRequest();
clientRequest.setGrantType('refresh_token');
clientRequest.setRefreshToken('INSERT_REFRESH_TOKEN');
//GlideOAuthClient
var client = new sn_auth.GlideOAuthClient();
//GlideOAuthClientResponse
var tokenResponse = client.requestTokenByRequest('INSERT_APPLICATION_REGISTRY_NAME', clientRequest);
//GlideOAuthToken
var token = tokenResponse.getToken();
gs.debug("Access Token: " + token.getAccessToken());