OAuth 2.0 integration in ServiceNow enables secure authentication and authorization for REST API communications between ServiceNow and external systems. This integration solves the critical business problem of maintaining secure, token-based authentication without hardcoded passwords, supporting modern API security standards required by enterprise applications. ServiceNow administrators and integration developers use OAuth 2.0 to establish trust relationships with third-party systems while maintaining proper access controls. ServiceNow supports bidirectional OAuth 2.0 flows, acting as both an OAuth client (consuming external APIs) and OAuth provider (exposing ServiceNow APIs to external applications). The primary automation patterns include automated token refresh, JWT validation, and secure credential storage using Connection & Credential Aliases within the ServiceNow platform's native REST integration framework.
Prerequisites
- •ServiceNow Paris release or later with OAuth 2.0 framework support
- •System Administrator role or oauth_admin role in ServiceNow
- •External system OAuth 2.0 provider configuration access
- •Integration Hub Starter license or higher for advanced OAuth flows
- •Understanding of REST API concepts and JSON Web Tokens (JWT)
- •Network connectivity between ServiceNow instance and OAuth provider endpoints
- •Valid SSL certificates for HTTPS communication
Architecture Overview
ServiceNow OAuth 2.0 integration uses native OAuth Entity and OAuth Provider records to manage authentication flows, with credentials securely stored in Connection & Credential Alias records. Authentication is established through the OAuth 2.0 authorization code flow or client credentials flow, with access tokens automatically managed by ServiceNow's OAuth framework and refresh tokens stored encrypted in the credential store. Data flows are typically outbound from ServiceNow to external OAuth-protected APIs using RESTMessageV2 or Scripted REST APIs, triggered by business rules, scheduled jobs, or Integration Hub flows. A MID Server is not required for OAuth 2.0 authentication itself, but may be needed if the target OAuth provider is behind a firewall or requires specific network routing. Rate limiting follows the external OAuth provider's API quotas, with ServiceNow automatically handling token refresh to maintain continuous connectivity within those limits.
Sourdough: ServiceNow Monitoring and Analytics
A Chrome extension for ServiceNow Admins and Developers with essential tools, analytics, graphs and monitoring features.
Free to install. Pro $5/month after a 14-day no-card trial.
Pro requires the ServiceNow admin role. Upgrade inside the extension.
Implementation Steps
Create OAuth Entity record for external system registration
Navigate to System OAuth > Application Registry and click New to create a new OAuth API endpoint. Select 'Connect to a third party OAuth Provider' and enter the OAuth provider's authorization URL, token URL, and client credentials obtained from the external system. Fill in the Client ID, Client Secret, and Default Grant Type (typically 'authorization_code' or 'client_credentials'). Configure the redirect URL to point back to your ServiceNow instance using the format https://your-instance.service-now.com/oauth_redirect.do. Save the record and note the generated Name field value, as this will be referenced in your REST message configurations.
Configure OAuth Provider record with endpoint details
Navigate to System OAuth > OAuth Provider and create a new provider record that corresponds to your external OAuth system. Enter the Authorization URL, Token URL, and Token Revocation URL from the external OAuth provider's documentation. Set the Default Grant Type to match your use case (authorization_code for user-based flows, client_credentials for service-to-service). Configure the Token Request Authentication method (typically 'Send client credentials in body' or 'HTTP Basic Authentication'). Specify any required scope values in the Default Scope field, separating multiple scopes with spaces or commas as required by the provider.
Create Connection Alias for OAuth endpoint reference
Navigate to Connections & Credentials > Connection & Credential Aliases and create a new Connection Alias record. Set the Type to 'Connection' and enter a meaningful name like 'External_System_OAuth_Connection'. In the Connection URL field, enter the base URL of the external OAuth-protected API (not the OAuth authorization URLs). Set the Connection timeout and Read timeout values appropriate for your external system (typically 30000ms each). This Connection Alias will be referenced by your REST messages and Integration Hub flows to establish the target endpoint for OAuth-authenticated API calls.
Create Credential Alias with OAuth Entity reference
In the same Connections & Credentials module, create a new Credential Alias with Type set to 'OAuth 2.0'. Enter a descriptive name and link this credential to the OAuth Entity created in step 1 using the OAuth Entity reference field. If using authorization code flow, you'll need to complete the initial authorization by clicking the 'Get OAuth Token' button and following the redirect to the external system for user consent. For client credentials flow, the token will be automatically obtained on first use. Verify that the OAuth Entity Name field matches exactly with the Name from your OAuth Entity record.
Create REST Message with OAuth authentication configuration
Navigate to System Web Services > Outbound > REST Message and create a new REST Message record for your OAuth-protected API calls. Set the Endpoint URL to reference your Connection Alias using the format '${credential:connection_alias_name}'. In the Authentication section, select 'OAuth 2.0' as the Authentication Type and reference your Credential Alias in the OAuth Profile field. Create HTTP Methods under this REST Message for each API operation you need to perform (GET, POST, PUT, DELETE). Configure appropriate HTTP headers, request body content, and response parsing for each method based on the external API specification.
Implement REST Message calls with proper error handling
Create a Script Include or Business Rule that utilizes your OAuth-configured REST Message for actual API communication. Instantiate the REST Message using RESTMessageV2, execute the HTTP method, and implement proper error handling for OAuth-specific scenarios like token expiration. ServiceNow automatically handles token refresh, but your code should check for 401 Unauthorized responses and retry logic. Always validate the response status and parse JSON responses safely to prevent script errors. Log important OAuth events to the System Log for troubleshooting and audit purposes.
var rm = new RESTMessageV2('Your_REST_Message_Name', 'get');
rm.setStringParameterNoEscape('endpoint', 'https://api.external-system.com/data');
try {
var response = rm.execute();
var httpStatus = response.getStatusCode();
if (httpStatus == 200) {
var responseBody = response.getBody();
var jsonResponse = JSON.parse(responseBody);
gs.info('OAuth API call successful: ' + jsonResponse);
} else if (httpStatus == 401) {
gs.error('OAuth token may be expired, automatic refresh should occur on retry');
}
} catch (ex) {
gs.error('OAuth REST call failed: ' + ex.getMessage());
}Configure ServiceNow as OAuth Provider for external applications
Navigate to System OAuth > Application Registry and click New, then select 'Create an OAuth API endpoint for external clients'. Enter the external application's details including Client ID, Client Secret, and allowed redirect URIs for the authorization code flow. Configure the Token Lifetime, Refresh Token Lifetime, and allowed scopes based on your security requirements. Set up proper access controls by defining which ServiceNow tables and operations the external client can access through the REST API. Test the OAuth provider configuration using tools like Postman or curl to verify token generation and API access work correctly.
Test and validate OAuth token flows with comprehensive logging
Execute comprehensive testing of both inbound and outbound OAuth flows using the REST API Explorer and external testing tools. Verify that access tokens are properly generated, refresh tokens work automatically, and token expiration is handled gracefully. Check the OAuth Token (oauth_token) table in ServiceNow to monitor active tokens and their expiration times. Enable OAuth debug logging by setting the log level to 'Debug' for the 'com.snc.integration.oauth' source in System Logs > System Log > Log Levels. Document your OAuth configuration settings and test results for future maintenance and troubleshooting reference.
// Test OAuth token validation in a Scripted REST API
(function process(request, response) {
var token = request.getHeader('Authorization');
if (!token || !token.startsWith('Bearer ')) {
response.setStatus(401);
response.getWriter().write('Missing or invalid OAuth token');
return;
}
var accessToken = token.substring(7); // Remove 'Bearer '
var tokenGR = new GlideRecord('oauth_token');
tokenGR.addQuery('access_token', accessToken);
tokenGR.query();
if (tokenGR.next() && tokenGR.expires > gs.nowDateTime()) {
response.setStatus(200);
response.getWriter().write('Valid OAuth token');
} else {
response.setStatus(401);
response.getWriter().write('Expired or invalid OAuth token');
}
})(request, response);Common Use Cases
Automated incident creation from external monitoring systems
External monitoring tools like Datadog or New Relic use OAuth 2.0 to authenticate with ServiceNow's REST API and automatically create incident records when system alerts are triggered. The monitoring system acts as an OAuth client, obtaining access tokens to call ServiceNow's Table API and create incidents with proper assignment groups and priority levels. This eliminates manual ticket creation and ensures consistent incident formatting while maintaining secure authentication without embedded passwords in monitoring configurations.
Employee onboarding workflow with HR system integration
ServiceNow integrates with HR systems like Workday or BambooHR using OAuth 2.0 client credentials flow to automatically retrieve new employee data and trigger onboarding workflows. When new employees are added to the HR system, ServiceNow polls the HR API using OAuth-authenticated REST calls to create user accounts, assign equipment requests, and initiate access provisioning tasks. The integration maintains data synchronization between HR records and ServiceNow user profiles while respecting both systems' security requirements and audit trails.
Third-party application access to ServiceNow CMDB data
External asset management or network discovery tools authenticate to ServiceNow using OAuth 2.0 authorization code flow to read and update Configuration Management Database (CMDB) records. These applications obtain user consent through OAuth authorization and use refresh tokens to maintain long-term access to ServiceNow's Table API for CI synchronization. The OAuth provider configuration in ServiceNow controls which CMDB tables and operations each external application can access, ensuring proper data governance and security.
Mobile application authentication for field service technicians
Custom mobile applications used by field service technicians authenticate to ServiceNow using OAuth 2.0 with PKCE (Proof Key for Code Exchange) for enhanced security on mobile devices. The mobile app guides technicians through OAuth login, obtains access tokens, and uses ServiceNow REST APIs to view assigned work orders, update task status, and upload completion photos. OAuth token refresh happens automatically in the background, maintaining seamless user experience while ensuring secure API access throughout the technician's workday.
Automated change management approvals from deployment pipelines
CI/CD deployment pipelines integrate with ServiceNow using OAuth 2.0 client credentials to create normal change requests and check approval status before deploying code to production environments. The deployment automation authenticates to ServiceNow, creates change records with deployment details, waits for approval workflow completion, and proceeds with deployment only after receiving approval confirmation. This integration ensures all production deployments follow proper change management processes while maintaining automated deployment capabilities and audit compliance.
Troubleshooting
401 Unauthorized error with message 'invalid_token' on REST API calls
First, check the OAuth Token (oauth_token) table to verify if your access token exists and hasn't expired by comparing the 'expires' field with current date/time. If the token is expired, ServiceNow should automatically attempt to refresh it using the refresh token, so verify that your OAuth Entity record has the correct Token URL configured. Check the System Log for OAuth-related errors during token refresh attempts, and ensure the external OAuth provider hasn't revoked or changed the client credentials.
OAuth authorization redirect fails with 'redirect_uri_mismatch' error
Navigate to your OAuth Entity record and verify that the Redirect URL exactly matches what's configured in the external OAuth provider system, including protocol (https), domain name, and path. The redirect URL should typically be https://your-instance.service-now.com/oauth_redirect.do for ServiceNow instances. Check for trailing slashes, case sensitivity, or URL encoding issues that might cause mismatches. Also verify that your ServiceNow instance is accessible from the OAuth provider's servers and not blocked by firewalls.
OAuth token refresh fails with 'invalid_grant' error in System Logs
This error typically indicates that the refresh token has expired or been revoked by the OAuth provider. Check your OAuth Provider record to ensure the Token URL is correct and accessible from your ServiceNow instance. Navigate to the OAuth Token table and delete any stale token records for the affected OAuth Entity, then re-authorize the connection by going to your Credential Alias and clicking 'Get OAuth Token' to complete a fresh authorization flow. Review the external OAuth provider's token lifetime settings to ensure refresh tokens aren't expiring too quickly.
REST Message execution hangs or times out during OAuth token acquisition
Check your Connection Alias timeout settings and increase the Connection timeout and Read timeout values if the OAuth provider has slow response times. Verify network connectivity to the OAuth provider's token endpoint by testing the URL directly from your ServiceNow instance. Review the OAuth Provider record to ensure all endpoint URLs are correct and use HTTPS. Check if a MID Server is required for network access to the OAuth provider and configure the REST Message to use the appropriate MID Server if necessary.
External applications receive 'insufficient_scope' errors when calling ServiceNow APIs
Review the OAuth Entity record for the external application and verify that the configured scopes match what the application is requesting during authorization. Check the external application's OAuth client configuration to ensure it's requesting appropriate scopes during the authorization flow. For custom scopes, ensure they're properly defined in your ServiceNow OAuth Provider configuration and map to the correct table and operation permissions. Test the authorization flow manually to confirm that the requested scopes are being granted and included in the access token.
JWT token validation failures with 'invalid_signature' errors in custom OAuth implementations
Verify that the JWT signing algorithm specified in your OAuth Provider record matches what the external system is using to sign tokens (commonly RS256 or HS256). For RS256 signatures, ensure the public key certificate is correctly configured in ServiceNow and matches the private key used by the token issuer. Check the JWT token's 'iss' (issuer) and 'aud' (audience) claims to ensure they match your ServiceNow OAuth configuration. Use online JWT debugging tools to decode and validate the token structure before troubleshooting ServiceNow-specific validation issues.
Pro Tips
- →Implement OAuth token caching strategies by creating custom Script Includes that check token expiration before making REST calls, reducing unnecessary token refresh requests and improving API performance. Store frequently accessed tokens in GlideRecord queries with indexed fields for faster retrieval during high-volume integrations.
- →Configure OAuth scope restrictions at the table level using Access Control Lists (ACLs) to ensure external OAuth clients can only access specific ServiceNow data they need, following the principle of least privilege. Create custom scopes for different integration patterns and map them to specific table operations for granular security control.
- →Use ServiceNow's OAuth audit capabilities by enabling OAuth-specific logging sources and creating custom reports on the oauth_token and oauth_entity_profile tables to monitor token usage patterns, identify potential security issues, and track integration performance metrics over time.
- →Implement circuit breaker patterns in your OAuth REST integrations by tracking consecutive failures and temporarily disabling OAuth calls when external systems are unavailable, preventing cascading failures and reducing unnecessary token refresh attempts during system outages.
- →Leverage ServiceNow's OAuth 2.0 PKCE support for mobile and single-page applications by configuring the OAuth Entity with PKCE enabled, providing enhanced security for public OAuth clients that cannot securely store client secrets.
- →Create reusable OAuth configuration templates using Update Sets that include pre-configured OAuth Entities, Providers, and Connection Aliases for common integration patterns, enabling faster deployment across multiple ServiceNow instances and maintaining consistent security configurations.
Known Limitations
- —ServiceNow's OAuth 2.0 implementation has a maximum token lifetime of 7200 seconds (2 hours) for access tokens and 31,536,000 seconds (1 year) for refresh tokens, which may not align with some external systems' security requirements. Custom token lifetime configurations require careful consideration of security policies and integration reliability needs.
- —OAuth token storage in ServiceNow is limited to 1000 active tokens per OAuth Entity by default, which can cause issues in high-volume integrations with multiple concurrent users or service accounts. Monitor token usage patterns and implement token cleanup jobs to prevent hitting these limits in production environments.
- —The OAuth 2.0 Device Authorization Grant (RFC 8628) flow is not natively supported in ServiceNow, limiting integration options for IoT devices and command-line applications that cannot display web-based authorization interfaces. Custom implementations may be required for these specific use cases using Scripted REST APIs and custom token management.
- —ServiceNow's OAuth JWT validation only supports RSA and HMAC signing algorithms, with limited support for newer algorithms like EdDSA or elliptic curve signatures. This may require coordination with external OAuth providers to ensure compatible signing methods are used for token validation.
- —Cross-domain OAuth redirects may face browser security restrictions with modern CORS policies and SameSite cookie settings, potentially affecting OAuth authorization flows for applications hosted on different domains than the ServiceNow instance. Additional configuration may be required for third-party OAuth integrations.
Frequently Asked Questions
Can ServiceNow act as both an OAuth client and provider simultaneously in the same instance?
Yes, ServiceNow can function as both an OAuth 2.0 client and provider within the same instance, using different configurations for each role. As a client, ServiceNow uses OAuth Entity records to consume external OAuth-protected APIs, while as a provider, it uses Application Registry entries to allow external applications to access ServiceNow APIs. These configurations are independent and can coexist without conflicts, enabling comprehensive OAuth integration scenarios for enterprise environments.
How does ServiceNow handle OAuth token refresh automatically, and can this process be customized?
ServiceNow automatically handles OAuth token refresh when the current access token expires, using the stored refresh token to obtain a new access token without user intervention. This process occurs transparently during REST API calls when a 401 Unauthorized response is received with an expired token. The refresh logic can be customized through Business Rules on the oauth_token table or by implementing custom refresh logic in Script Includes that override the default RESTMessageV2 behavior for specific integration requirements.
What's the difference between using OAuth 2.0 in REST Messages versus Integration Hub flows?
REST Messages with OAuth 2.0 provide direct, code-based control over API authentication and are ideal for custom integrations requiring specific error handling or complex request formatting. Integration Hub OAuth flows offer a visual, low-code approach with pre-built OAuth handling and are better suited for standard integration patterns with supported systems. Integration Hub automatically manages OAuth token lifecycle and provides built-in retry logic, while REST Messages require manual implementation of these features but offer greater flexibility for custom OAuth scenarios.
How can I monitor and audit OAuth token usage across my ServiceNow instance?
Monitor OAuth activity through the oauth_token table to track active tokens, expiration times, and usage patterns, and create scheduled reports to identify unused or frequently refreshed tokens. Enable debug logging for the 'com.snc.integration.oauth' source to capture detailed OAuth transaction logs in System Logs. Use Performance Analytics to create dashboards showing OAuth integration performance metrics, token refresh rates, and authentication failure trends. Additionally, implement custom Business Rules on OAuth-related tables to log security events and integration usage for compliance reporting.
Can ServiceNow OAuth configurations work with on-premises systems behind firewalls?
Yes, ServiceNow can integrate with on-premises OAuth providers using MID Servers to establish secure connections through firewalls and private networks. Configure your REST Messages to use a MID Server that has network access to the internal OAuth provider endpoints. The MID Server handles the OAuth token exchange and API communication while maintaining security boundaries between ServiceNow cloud and on-premises systems. Ensure proper firewall rules allow HTTPS communication between the MID Server and internal OAuth endpoints for successful token acquisition and refresh operations.
What happens to existing OAuth integrations when upgrading ServiceNow versions?
ServiceNow OAuth configurations are generally preserved during platform upgrades, but new releases may introduce enhanced OAuth features or security requirements that affect existing integrations. Review release notes for OAuth-related changes and test all OAuth integrations in a sub-production instance before upgrading production. Some upgrades may require updating OAuth Entity configurations to support new security features like PKCE or updated token validation methods. Plan for potential re-authorization of OAuth connections if the upgrade introduces breaking changes to the OAuth framework or security policies.
How do I implement proper error handling for OAuth failures in automated ServiceNow workflows?
Implement comprehensive error handling by checking HTTP response codes in your OAuth REST calls and creating specific error handling paths for different OAuth failure scenarios like token expiration (401), insufficient permissions (403), and rate limiting (429). Use try-catch blocks around RESTMessageV2 calls and implement exponential backoff retry logic for transient OAuth errors. Create custom error logging that captures OAuth-specific failure details and implement alerting mechanisms to notify administrators of persistent OAuth authentication failures that might indicate configuration issues or external system problems.
Test Your Knowledge
Quick 3-question quiz — see how your ServiceNow skills stack up.
A list view on a table with millions of records is slow. Best fix?
Select an answer to continue