logo

NJP

How to authenticate with refresh token and Bearer Authorization header – ServiceNow Oauth 2.0

Import · May 15, 2020 · article

Since Orlando, there is a new feature for configuring Oauth 2.0. Now you can choose how you can authenticate with Oauth 2.0: by sending credentials in request body or as a Basic Authorization header, however not using Bearer.

This makes things a little bit easier, however it could be enhanced to allow more situations where authenticating could be done with 0 code.

For now on, let’s looks at an easy way to get access token when we are required to use refresh token which we can use in our Authorization Bearer HTTP header:

  1. Create application registry for third party Oauth 2.0 application
  2. Set up client_id and client_secret, set default grant type to ‘Client credentials’.
  3. Set Token URL as provided by 3rd party.
  4. Use example code below to execute your REST Message:
var oAuthClient = new sn_auth.GlideOAuthClient();
// Store the refresh token in sys_properties
var params = {grant_type:"refresh_token", refresh_token: gs.getProperty('xxx.refresh_token')};
var request_payload = new global.JSON().encode(params);
// requestToken first param is the Name in Application Registry
, request_payload is what is added to the Request body as chosen in Oauth profile
var tokenResponse = oAuthClient.requestToken("Application Name", request_payload);
var token = tokenResponse.getToken();

var restMessage = new sn_ws.RESTMessageV2('REST MESSAGE XXX', 'Method XXX');
// put a token with token.getAccessToken()
restMessage.setRequestHeader("Authorization", "Bearer " + token.getAccessToken());

var response = restMessage.execute();
var responseBody = response.getBody();
gs.info(responseBody);

Note: this way any calls that require Authorization Bearer header can be used. GlideOAuthClient can be modified to retrieve access token in any way 3rd party supports. It gets the token from the database, if it’s expired – makes a call to get a new one.

Hopefully a third OOTB option will be added to send credentials as a Bearer Authorization header or at least we will be allowed to modify HTTP Headers via Oauth API Scripts so we do not need to use the same script in our REST message executions and actual authentication will be controlled via main Oauth config profile.

View original source

https://servicenowthink.wordpress.com/2020/05/15/how-to-authenticate-with-refresh_token-and-bearer-authorization-header-servicenow-oauth-2-0/