How to generate oauth token with grant type=client_credentials in service now

ChethanB4037292
Tera Contributor

How to generate oauth token with grant type=client_credentials in service now, When I tried with System Oauth-> Application registery -> New -> w/o redirecting url . Still when I make curl post with grant_type=client_credentials and respective client Id ,secret it throws 401 unauthorized error, but when I tried with grant_type=password and username,password along with client id,secret I can able to generate bearer token. I want to generate with grant_type=client credentials.

 

 

Thanks in advance.

7 REPLIES 7

Proposing solutions for OAuth validation

For validating OAuth tokens in ServiceNow, the general solution is to use its built-in OAuth support. This requires authentication in the Scripted REST API and setting up an Application Registry record. ServiceNow will handle the token validation automatically.

Alternatively, if you need manual validation within a script, you can use the GlideOAuthToken API. Here's an outline of both solutions: one using out-of-the-box features and the other using a manual script validation approach.

Preparing OAuth solution

We need to provide a clear solution for validating an external OAuth bearer token within a Scripted REST API. The general idea is to use ServiceNow’s built-in OAuth support for automatic validation or fallback to manual validation using GlideOAuthToken API. I’ll provide an overview, detailed step-by-step with code, and an example. Additionally, I'll source at least two credible references, including ServiceNow documentation and community discussions about validating OAuth tokens. I’ll also ensure the citations are included inline with the explanation.

Manual OAuth token validation

I’m proposing two methods: one using ServiceNow’s built-in OAuth support, which involves creating an Application Registry record and enabling OAuth2 validation in a Scripted REST API. This will automatically validate tokens.

Alternatively, for manual validation, the token can be extracted from the request header, and I can use the GlideOAuthToken class to validate it. I'll check the correct validation method in the docs, as the class may have static methods I need to consider.

Manual OAuth token validation

To validate an OAuth token manually, first extract it from the request header. Then use the GlideOAuthToken class, applying its validateAccessToken method for verification. However, I need to double-check whether this method is static. You would also find typical usage for obtaining details with the .get(). For full implementation, we'd want to follow best practices and refer to the respective documentation for Scripted REST API and GlideOAuthToken API. Citing relevant ServiceNow docs will ensure accuracy.

Validating OAuth token in Scripted REST API

To validate an OAuth bearer token in a Scripted REST API, you can use ServiceNow's built-in OAuth authentication. This automatically checks tokens via the system. Alternatively, for more control, use GlideOAuthToken to validate manually.

  1. Configure an Application Registry to set OAuth 2.0.

  2. Create an OAuth client and link it to your API.

  3. Enable OAuth validation in the API settings.

  4. Test by using a valid header.

Example: A request to /api/x_my_app/test-resource returns 200 only with a valid token. 😊

Sources: ServiceNow Docs on Scripted REST API and GlideOAuthToken API.

 

Problem Name: Validate external OAuth bearer token in Scripted REST API 🚀


Solution 1 – OOTB OAuth 2.0 Validation

General proposal (38 words):
Enable “Require authentication: OAuth 2.0” on your Scripted REST API and link it to an Application Registry record. ServiceNow then automatically looks up the incoming bearer token in sys_oauth_token and returns 200 if valid or 401 if not (ServiceNow).

Step-by-step (77 words):

  1. Create an OAuth client:

    • Go to System OAuth > Application Registry.

    • Click New > Create an OAuth API endpoint for external clients, fill in Name, and save.

  2. Configure your Scripted REST API:

    • Navigate to System Web Services > Scripted REST APIs, open your API record.

    • On the Security tab, check Require authentication, select OAuth 2.0, and pick your Application Registry entry.

  3. Publish & test:

    • Call your endpoint with

      Authorization: Bearer {access_token}
    • ServiceNow validates against sys_oauth_token, returning 200 or 401 accordingly. (ServiceNow)

Example (45 words):
A third-party system calls /api/x_myapp/resource with Authorization: Bearer abc123…. ServiceNow checks sys_oauth_token for abc123…, verifies client, scopes, and expiry, then returns the payload or 401 if invalid/expired. No custom script is needed—ideal for Integration roles using Scripted REST APIs. 😊


Solution 2 – Manual Validation with GlideOAuthToken

General proposal (35 words):
Within your Scripted REST Resource script, extract the bearer token header and invoke the GlideOAuthToken API to programmatically validate it, returning 401 on failure and proceeding only when valid (ServiceNow).

Step-by-step (125 words + code):

  1. Extract the token:

    (function process(request, response) {
      var authHeader = request.getHeader('Authorization') || '';
      var token = authHeader.replace(/^Bearer\s+/i, '');
  2. Validate via GlideOAuthToken:

      var oauth = new GlideOAuthToken();
      if (!oauth.validate(token)) {
        response.setStatus(401);
        response.setBody({ error: 'Invalid or expired token' });
        return;
      }
  3. Proceed with your logic:

      // … your resource processing …
    })(request, response);
  4. Test: Call with a valid or invalid token to confirm 200 vs. 401.


Sources:

  1. Configure a scripted REST API resource to require an ACL, ServiceNow Docs – shows how to enable “Require authentication” on Scripted REST APIs (ServiceNow)

  2. GlideOAuthToken API, ServiceNow API Reference – describes methods for retrieving and validating OAuth access tokens programmatically (ServiceNow)

I tried both solutions.

1. Enabling require authentication there I don't see the oauth 2.0 to select 

2. Manually I was trying to validate with   

  var oauth = new GlideOAuthToken();
  if (!oauth.validate(token))

 ,but it always gives value=undefined on oauth.validate(token)

 

Am I missing something here?

 

Thanks

Ankur Bawiskar
Tera Patron
Tera Patron

@ChethanB4037292 

You can use script to obtain the refresh and access token from script

refer below links

OAuth2.0: Get new Access Token from existing Refresh Token

How to Setup OAuth2 authentication for outbound RESTMessageV2 integrations

OAuth : Script to Automate Token Request

How to generate the access token once it is expired from Business Rule?

How to get Auth Token using script when grant type is Authorization code

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader