Setup a scheduled job to ensure refresh tokens do not expire.
We recommend customers using outbound OAuth use this scheduled job script to ensure outbound OAuth connections remain alive, as explained in this KB Article from ServiceNow.
Without this job, the refresh token will eventually expire which means ServiceNow will no longer be able to retrieve an access token. This in turn will cause outbound requests to fail.
If your OAuth service is including refresh tokens with each access token request, this job may not be required.
This script has been reformatted from the KB Article for ease of use.
function refreshAccessToken(requestorId, oauthProfileId, token) {
if (!(token && requestorId && oauthProfileId)) return;
var tokenRequest = new sn_auth.GlideOAuthClientRequest();
tokenRequest.setGrantType("refresh_token");
tokenRequest.setRefreshToken(token.getRefreshToken());
tokenRequest.setParameter('oauth_requestor_context','sys_rest_message');
tokenRequest.setParameter('oauth_requestor', requestorId);
tokenRequest.setParameter('oauth_provider_profile',oauthProfileId);
var oAuthClient = new sn_auth.GlideOAuthClient();
var tokenResponse = oAuthClient.requestTokenByRequest(null,tokenRequest);
var error = tokenResponse.getErrorMessage();
if (error) gs.warn("Error:" + tokenResponse.getErrorMessage());
}
function isExpired(expiresIn, withinSeconds) {
if (expiresIn > withinSeconds) return false;
return true;
}
function getToken(requestorId, oauthProfileId) {
if (!requestorId || !oauthProfileId) return null;
var client = new sn_auth.GlideOAuthClient();
return client.getToken(requestorId, oauthProfileId);
}
function checkAndRefreshAccessToken(grRestMessage) {
if (grRestMessage.getValue("authentication_type") != "oauth2") return false;
var accountMsg = grRestMessage.getValue("name");
if (!accountMsg)
accountMsg = grRestMessage.getUniqueValue();
accountMsg = "Account=\"" + accountMsg + "\"";
var token = getToken(grRestMessage.getUniqueValue(), grRestMessage.getValue('oauth2_profile'));
var accessToken = token.getAccessToken();
if (accessToken) {
if (!isExpired(token.getExpiresIn(), 300)) return;
}
if (!token.getRefreshToken()) {
gs.error("No OAuth refresh token for Rest Message. Manual reauthorization required. " + accountMsg);
return;
}
if (isExpired(token.getRefreshTokenExpiresIn(), 0)) {
gs.error("OAuth refresh token for Rest Message is expired. Manual reauthorization required. " + accountMsg);
return;
}
gs.info("Refreshing oauth access token for Rest Message account. " + accountMsg);
refreshAccessToken(grRestMessage.getUniqueValue(), grRestMessage.getValue('oauth2_profile'), token);
}
var grAccount = new GlideRecord("sys_rest_message");
grAccount.addQuery("authentication_type", "oauth2");
grAccount.addNotNullQuery("oauth2_profile");
grAccount.query();
while (grAccount.next()) {
checkAndRefreshAccessToken(grAccount);
}Follow this guide to learn how to setup an OAuth Connection in Unifi.
This document will guide you through the process of configuring an OAuth Connection for your Unifi Integration (ServiceNow to ServiceNow). This will involve making configuration changes in both the identity provider and identity consumer instances. As such, this guide will examine the changes for each instance separately on the subsequent pages.
In this guide, you will configure an additional OAuth Connection to another ServiceNow instance as part of the Incident Guide Integration (created when following the ). The external instance will act as the Identity Provider whilst the original instance will act as the Identity Consumer.
It is assumed that the Integration has been configured, packaged and moved to the external instance (see for details). Therefore, the Process, Web Service & Integration are already in place (if not, please ensure that at least those elements are in place before continuing).
These are the configuration changes to be made in the identity provider instance when setting up an OAuth Connection.
In native ServiceNow, navigate to System OAuth > Application Registry and click New.
On the interceptor page, click Create an OAuth API endpoint for external clients.
The fields to be configured for the Application Registry record are as follows:
*These values are to be left as-is.
Your Application Registries New Record should look like this:
Submit the record.
If you haven't already done so, you will need to create an Inbound user in this instance. See for details.
In Unifi Integration Designer, navigate to Connections and click New.
The fields to be configured for the New Connection modal are as follows:
The format of the Endpoint URL is as follows:
https://<your_consumer_instance>.service-now.com/<your_consumer_resource_path>
The entire Endpoint URL can be easily obtained from the automatically created Message Resource on the Unifi Scripted REST API (displayed in the widget at the top of the Connections page) in the other instance.
Your New Connection modal should look like this:
Submit and view to further configure the Connection.
The fields to be configured for the Details form are as follows:
Your Details form should look like this:
Save the Connection.
At this point you can perform a basic Connection test. For instructions, see .
Next, configure the Identity Consumer Instance.
The number of seconds a refresh token issued will be good for
8,640,000 (default value - automatically populated)
Access Token Lifespan*
The number of seconds an access token issued will be good for
1,800 (default value - automatically populated)
Comments
Comments about the OAuth app
<Your description of the purpose of the OAuth entity>
The user profile used by the external system for authentication. An active connection must be found for the user to gain access.
lookup: <Your Inbound User>
Name
Name of the OAuth app
<Your Unique Name>
Client ID*
The client id of the OAuth app
[read-only] (automatically generated)
Client Secret*
The client secret of the OAuth app
Leave [Blank] to automatically generate
Environment
The environment this connection applies to.
'Pre-Production'
Endpoint URL
The external system's access URL.
<External system Endpoint URL>
Active
Use this connection for the integration when true.
<true>
Authentication
The authentication method to use for this connection.
'Basic'
User
The username used in basic authentication.
<external.system.user>
Password
The password used in basic authentication.
<External system user password>
Refresh Token Lifespan*
Inbound user
These are the configuration changes to be made in the identity consumer instance when setting up an OAuth Connection.
In native ServiceNow, navigate to System OAuth > Application Registry and click New.
On the interceptor page, click Connect to a third party OAuth Provider.
The fields to be configured for the Application Registry record are as follows:
*This value is to be left as-is.
Your Application Registries New Record should look like this:
Right-click and Save to remain on the record.
Validate that the OAuth Entity Profiles related list has been populated with the following values:
Name: <Your Unique Name> default_profile
Is default: true
Grant type: Resource Owner Password Credentials
In Unifi Integration Designer, navigate to Connections and click New.
The fields to be configured for the New Connection modal are as follows:
The format of the Endpoint URL is as follows:
https://<your_provider_instance>.service-now.com/<your_provider_process_api>
The entire Endpoint URL can be easily obtained from the automatically created Message Resource on the Unifi Scripted REST API (displayed in the widget at the top of the Connections page in the other instance).
Your New Connection modal should look like this:
Submit and view to further configure the Connection.
The fields to be configured for the Details form are as follows:
Your Details form should look like this:
Save the Connection.
Once you have saved the Connection, the 'Get OAuth Token' button is available.
Click Get OAuth Token.
On the modal that pops up, enter the Username & Password (for the Inbound user of the Identity Provider Instance).
Click Get OAuth Token.
The 'OAuth token flow completed successfully' info message is displayed. Close the modal.
Congratulations. You have successfully configured both halves of the OAuth Connection.
To future proof your OAuth connection, please consider setting up the .
The Default Grant Type used to establish the OAuth token
'Resource Owner Password Credentials'
Refresh Token Lifespan*
The number of seconds a refresh token issued will be good for
8,640,000 (default value - automatically populated)
Token URL
OAuth token endpoint to retrieve access and refresh tokens
'https://<your-provider-instance>.service-now.com/oauth_token.do'
Comments
Comments about the OAuth app
<Your description of the purpose of the OAuth entity>
Name
Name of the OAuth app
<Your Unique Name>
Client ID
The client id of the OAuth app
The Client ID from the Identity Provider Instance
Client Secret
The client secret of the OAuth app
The Client Secret from the Identity Provider Instance
Environment
The environment this connection applies to.
'Pre-Production'
Endpoint URL
The external system's access URL.
<External system Endpoint URL>
Active
Use this connection for the integration when true.
<true>
Authentication
The authentication method to use for this connection.
'OAuth 2.0'
OAuth Profile
The OAuth Entity Profile to authenticate with.
'<Your Unique Name> default_profile' (as created/validated above)
Inbound user
The user profile used by the external system for authentication. An active connection must be found for the user to gain access.
lookup: <Your Inbound User>
Default Grant type















