Azure Auth Header

by cmatskas

HTML

<scritp src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core.js"></scritp>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data.min.js"></script>

JavaScript

debugger;

getCollections("GET", "collection", "student");

function getCollections(verb, resourceType, resourceId) {
  let azureApiVersion = "2016-07-11";
  let masterKey = "RTBA2c8HivHZ0un7wnl23rC1QNyzOUIpOiKGIVUJkuQbw3Vd8xVxIdhbI8IAEmfhjT5djis25JL6ODNZb0xLkw==";
  var key = stringToArrayBuffer(masterKey);
  console.log(key);
  console.log(arrayBufferToString(key));
  console.log(masterKey);
  let dateInRfc7231Format = moment().format("ddd, DD MMM YYYY HH:mm:ss");
  let dateWithTimeZone = dateInRfc7231Format + " GMT";
  console.info(dateWithTimeZone);
  let text = `${verb.toLowerCase()}\n${resourceType.toLowerCase()}\n${resourceId}\n${dateWithTimeZone.toLowerCase()}\n\n`;
  let hash = CryptoJS.HmacSHA256(text, masterKey);
  console.info(hash);
  return hash;
  /*var body = new Buffer(text, "utf8");  
    var signature = crypto.createHmac("sha256", key).update(body).digest("base64");  

    var MasterToken = "master";  

    var TokenVersion = "1.0";  

    return encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature);  

  var request = new XMLHttpRequest();
  request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  request.onreadystatechange = function() {   
    if (this.readyState == 4 && this.status == 200) {    
      alert('this.responseText');   
    } 
  }; 
  xhttp.open(httpVerb, url, true); 
  xhttp.send(null);*/
}

function stringToArrayBuffer(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

function arrayBufferToString(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function getCanonicalisedHeader() {
  let dateInRfc1123Format = "";
  let header = `x-ms-date:${dateInRfc1123Format}\nx-ms-version:${azureApiVersion}`;
  return header;
}