Forum Discussion

sai_reddy's avatar
2 years ago

Unable to authenticate Rest api with servicenow to get devices

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.