The CreatorCon Call for Content is officially open! Get started here.

Generate a new OAuth Refresh token once it is expired

Sharan Ellendul
Tera Contributor

Hi,

 

We are integrating ServiceNow with a third party tool. That third party tool wants to pull data from ServiceNow. So we have created a OAuth registry for Authentication purpose. The other tool uses only Client ID, Client Secret and Refresh token to generate Access token. Now for every certain period of time refresh token expires. How to automatically generate new Refresh token within the same ServiceNow instance itself, so that we can send that Refresh token to that tool via email from ServiceNow?

 

Thanks in Advance

Sharan

6 REPLIES 6

Mahathi
Mega Sage
Mega Sage

Hi @Sharan Ellendul ,

You can retrieve them from Oauth credential table.

Creating a schedule job can work:
Script to retrieve Access and Refresh tokens using GlideOAuthClient libraries

 

Also, refer to the  below articles for more clarity:

https://community.servicenow.com/community?id=community_blog&sys_id=d547f492db61d300fc5b7a9e0f9619d2

 

https://www.servicenow.com/community/developer-forum/will-oauth2-0-refresh-token-be-automatically-re...

 

If my answer helped in any way, please mark it as Correct & 👍Helpful

Thanks,

Mahathi




Satishkumar B
Giga Sage
Giga Sage

Hi @Sharan Ellendul 

 

 

 

// Query the OAuth registry record where OAuth tokens are stored
var oauthRegistry = new GlideRecord('oauth_registry');
oauthRegistry.addQuery('client_id', '<Your Client ID>');
oauthRegistry.query();

if (oauthRegistry.next()) {
    var refreshToken = oauthRegistry.refresh_token;
    var expirationTime = new GlideDateTime(oauthRegistry.refresh_token_expires_at);
    var currentTime = new GlideDateTime();

    // Check if the Refresh token is expired or expiring soon (e.g., within 24 hours)
    if (currentTime.compareTo(expirationTime) >= 0) {
        // Refresh token needs renewal, make a request to obtain a new one
        var tokenEndpoint = '/oauth_token.do';
        var requestBody = {
            grant_type: 'refresh_token',
            refresh_token: refreshToken,
            client_id: '<Your Client ID>',
            client_secret: '<Your Client Secret>'
        };

        // Make an HTTP request to ServiceNow's token endpoint to obtain a new Refresh token
        var response = gs.httpClient.post(tokenEndpoint, requestBody);
        var responseBody = JSON.parse(response.body);

        if (response.status == 200 && responseBody.refresh_token) {
            // Update the OAuth registry record with the new Refresh token
            oauthRegistry.refresh_token = responseBody.refresh_token;
            oauthRegistry.refresh_token_expires_at = responseBody.expires_at;
            oauthRegistry.update();

            // Send an email notification with the new Refresh token to the third-party tool
            var email = new GlideEmailOutbound();
            email.setSubject('New OAuth Refresh Token');
            email.setBody('Your new OAuth Refresh Token is: ' + responseBody.refresh_token);
            email.addRecipient('<Recipient Email>');
            email.send();
        } else {
            gs.error('Error refreshing OAuth tokens: ' + response.status + ' - ' + response.body);
        }
    }
}

 

 

 

If my answer helped in any way, please mark it as Correct & 👍 Helpful

 

 

 

Hi Satish,

 

There is not such table as "oauth_registry" to query. Assumed that table as oauth_entity but didn't find the field "refresh_token". Can you help in this?

 

Thanks,

Hi @Sharan Ellendul 

  • Query the oauth_credential table to retrieve the OAuth credentials.
  • Check if the refresh token is expired or about to expire.
  • Make a request to obtain a new refresh token.
  • Update the OAuth credential record with the new refresh token.
  • Send an email notification with the new refresh token.

 

 

 

Code to retrieve Access token and Refresh Token:

var oAuthClient = new sn_auth.GlideOAuthClient();
var requestor_context = 'test';
var requestor_id = 'abc@xyz.com';
var oauth_profile_id = '43d6bab3db849f009a6ff9b61d961957'; // profile ID [sys_id of  'OAuth Entity Profiles' (oauth_entity_profile) record in OAUTH registry  record]

var params = {grant_type:"password", username:'admin', password:'pwd', 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() ;

gs.log("AccessToken:" + access_token);
gs.log("AccessTokenExpiresIn:" + token.getExpiresIn());
gs.log(" RefreshToken:" + token.getRefreshToken());


Code to retrieve a new Access Token using Refresh token

var oAuthClient = new sn_auth.GlideOAuthClient();
var requestor_context = 'test';
var requestor_id = 'abc@xyz.com';
var oauth_profile_id = '43d6bab3db849f009a6ff9b61d961957'; // profile ID [sys_id of  'OAuth Entity Profiles' (oauth_entity_profile) record in OAUTH registry  record]

var params = {grant_type:"refresh_token", refresh_token:"<value_of_refresh_token>", 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() ;

gs.log("AccessToken:" + access_token);
gs.log("AccessTokenExpiresIn:" + token.getExpiresIn());gs.log(" RefreshToken:" + token.getRefreshToken());



Making an outbound REST call with the retrieved token

// make the outbound REST call with the retrieved token

var r = new sn_ws.RESTMessageV2('empukemburu03_outbound', 'Default GET'); 
//setting oauth profile and oauth requester profile
r.setAuthenticationProfile('oauth2', oauth_profile_id); 
r.setRequestorProfile(requestor_context, requestor_id);

var response = r.execute(); 
var responseBody = response.getBody(); 
var httpStatus = response.getStatusCode(); 

gs.log(responseBody);

 

 

 

 

--------------------------------------------------------------------------------------------------------------------
If my response proves useful, please indicate its helpfulness by selecting "Accept as Solution" and " Helpful." This action benefits both the community and me.