OAuth2.0: Get new Access Token from existing Refresh Token
Please hit Like or Bookmark this article if it helps.
Applicable to: Outbound Integrations from ServiceNow to third party applications using OAuth2.0
An Access Token in OAuth2.0 will expire at some point in time, and when they expire we need to request a new Access Token to keep the integration alive. We can utilize an existing refresh token to get a new Access Token. All you need to know before hand is the name of the OAuth2.0 Application Registry. If you dont know the name of your OAuth Application Registry, you can navigate to System OAuth -> Application Registry find your Application Registry, and copy the value in the Name field.
The below code will explain the logic to retrieve a new Access Token from an existing Refresh Token. You can use the below logic and tweak it according to your needs. You can use it in the Business Rules or Script Actions or Scheduled jobs.
/*This is the only information you need before hand*/
var Application_Registry_Name = 'Google Client';
/*Attempt to find the existing Refresh Token*/
var refreshToken = '';
var grOC = new GlideRecord('oauth_credential');
grOC.addEncodedQuery('type=refresh_token^expiresRELATIVEGT@minute@ahead@1^peer.name='+Application_Registry_Name);
grOC.query();
if(grOC.next()){
var Encrypter = new GlideEncrypter();
refreshToken = Encrypter.decrypt(grOC.token_received);
}
/*If a valid Refresh Token Exists, then request the new Access Token*/
if(JSUtil.notNil(refreshToken)){
//GlideOAuthClientRequest
var clientRequest = new sn_auth.GlideOAuthClientRequest();
clientRequest.setGrantType('refresh_token');
clientRequest.setRefreshToken(refreshToken);
//GlideOAuthClient
var client = new sn_auth.GlideOAuthClient();
//GlideOAuthClientResponse
var tokenResponse = client.requestTokenByRequest(Application_Registry_Name , clientRequest);
//GlideOAuthToken
var token = tokenResponse.getToken();
gs.log('Existing Refresh Token: '+refreshToken);
gs.log("New Access Token:" + token.getAccessToken());
gs.log("New Access Token Expires In:" + token.getExpiresIn()+' Seconds');
}else{
gs.log('Unable to find an existing refresh token');
}
Output:
*** Script: Existing Refresh Token: 1//0fXrIibvEWjnVCgYIARAAGA8SNwF-L9IruFmIV_HP1_tJipKCL-EKFx9AFm6hnzVNbr6Z9sEM1eV1QIGEeCVw3VFGfQnMwdxg_LM
*** Script: New Access Token:ya29.a0AfH6SMDdlqCawR_lSq1X5KZv2I3BGjbKaNvj3g5ISpULGcFaF0IO8xmdHvGfCbtWI6_Tc6rYELFyoK_Dbj1tnRLA9l0nX-Z0YK2S0PRfLx3QqGX61UdPtdW1mszMqFb0qs45nftw88hKA45nqrjpscFw5VCc48jxWaw
*** Script: New Access Token Expires In:3599 Seconds
Thank you,
Aman Gurram
ServiceNow Systems Integration Specialist.
References and Helpful links:
https://www.servicenow.com/community/developer-articles/oauth2-0-get-new-access-token-from-existing-refresh-token/ta-p/2313464