Question

Unable to authenticate Rest api with servicenow to get devices


Userlevel 1
Badge

Hi All,

I am trying to authenticate in servicenow using script but it is not working. It is throwing an error authentication failed status 401.

var ACCESS_ID = '123';
var ACCESS_KEY = 'abc';
var ACCOUNT_NAME = 'test';
var resourcePath = '/device/devices';

var epoch = (new Date()).getTime();
var id = 2;

var requestVars = 'GET' + epoch + resourcePath;

var HexUtil = 
{
  convertByteArrayToHex : function(byteArray)
  {
    var hex = "";
 
    byteArray.forEach(function(byteValue) { hex += HexUtil.convertByteToHex(byteValue); });
 
    return hex;  
  },
 
  convertByteToHex : function(b) 
  {
    var hexChar = ["0", "1", "2", "3", "4", "5", "6", "7","8", "9", "a", "b", "c", "d", "e", "f"];
  
    return hexChar[(b >> 4) & 0x0f] + hexChar[b & 0x0f];
  }
};
// Compute the HMACSHA256 hash using GlideDigest
var key = "key";
key = encodeURIComponent(key);
key = GlideStringUtil.base64Encode(key);
 
var msg = "message";
msg = encodeURIComponent(msg);
 
var mac = new GlideCertificateEncryption();
signature = mac.generateMac(requestVars, "HmacSHA256", ACCESS_ID);

var bytes = GlideStringUtil.base64DecodeAsBytes(signature);
var hex = HexUtil.convertByteArrayToHex(bytes);
var hexB64 = GlideStringUtil.base64Encode(hex);

var token = 'LMv1 ' + ACCESS_ID + ':' + signature + ':' + epoch;

gs.info('Devices = ' +token);

var httpRequest = new GlideHTTPRequest('https://' + ACCOUNT_NAME + '.logicmonitor.com/santaba/rest/device/devices');
httpRequest.addHeader('Content-Type', 'application/json');
httpRequest.addHeader('Authorization', token);
//httpRequest.addHeader('x-server-version', '3');
var response = httpRequest.getBody();

gs.log(response);

 

Could you please help me on this.


3 replies

Badge

I did have to add a response = httpRequest.get() before the getBody() call. 

Then I could actually get the response codes. However, I am still failing authentication! I’ll see if I can find the issue and let you know here! 

Userlevel 1
Badge

Hi Adam,

I tried working on this actually issue is here with cryptoJS which is not available by out of box.

I have created the same in Servicenow scoped application script include but still it is not working.

 

when I use the above script getting the signature length less and due to this authentication is not working.

Userlevel 4
Badge +5

@sai reddy Does this thread help at all?

 

Reply