Skip to content

Instantly share code, notes, and snippets.

@simone-gasparini
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simone-gasparini/29a0112e1872a5185be7 to your computer and use it in GitHub Desktop.
Save simone-gasparini/29a0112e1872a5185be7 to your computer and use it in GitHub Desktop.
Azure Event Hub SAS Token creation
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>
<script type="text/javascript" src="https://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<title>EVENT HUB - SAS Token Test</title>
</head>
<body>
<div class="col-md-4 col-md-offset-4 well" style="margin-top: 20px;">
<fieldset>
<legend>EVENT HUB - SAS Token Test</legend>
<div class="form-group">
<label for="NamespaceInput">NameSpace</label>
<input type="text" class="form-control" id="NamespaceInput" placeholder="Enter NameSpace" />
</div>
<div class="form-group">
<label for="KeyInput">SAS Key</label>
<input type="text" class="form-control" id="KeyInput" placeholder="Enter SAS Key" />
</div>
<div class="form-group">
<label for="KeyNameInput">SAS Key Name</label>
<input type="text" class="form-control" id="KeyNameInput" placeholder="Enter SAS Key Name" />
</div>
<div class="form-group">
<label for="PathInput">Path</label>
<input type="text" class="form-control" id="PathInput" placeholder="Enter Path" />
</div>
<div class="form-group">
<label for="DeviceNameInput">Device Name</label>
<input type="text" class="form-control" id="DeviceNameInput" placeholder="Enter Device Name" />
</div>
<div class="form-group">
<label for="BodyInput">Body</label>
<input type="text" class="form-control" id="BodyInput" placeholder="Enter Body" />
</div>
<button type="submit" id="SendButton" class="btn btn-sm btn-primary m-r-5 center-block">Send</button>
</fieldset>
</div>
<div class="col-md-10 col-md-offset-1 well" style="text-align: center;"><span id="TokenSpan"></span></div>
<script type="text/javascript">
var m_ServiceNamespace = "test-namespace";
var m_SasKey = "YOUR-TOKEN=";
var m_SasKeyName = "Test";
var MessagingResult = function(a, status, c, response) {
this.a = a;
this.status = status;
this.c = c;
this.response = response;
};
function consoleLog(obj) {
console.log(JSON.stringify(obj));
};
function test() {
sendMessage(
"your-path",
"sensor0001",
JSON.stringify({"temperature": 32.2, "humidity": 74.1}),
"application/json;type=entry;charset=utf-8",
consoleLog
);
};
$('#SendButton').on('click', function () {
m_ServiceNamespace = $("#NamespaceInput").val();
m_SasKey = $("#KeyInput").val();
m_SasKeyName = $("#KeyNameInput").val();
var securityToken = sendMessage(
$("#PathInput").val(),
$("#DeviceNameInput").val(),
$("#BodyInput").val(),
"text/plain;type=entry;charset=utf-8",
consoleLog
);
$("#TokenSpan").html("Generated Security Token<br/>&quot;" + securityToken + "&quot;");
});
// Function which creates the Service Bus SAS token.
function getToken(entityPath) {
var uri = "https://" + m_ServiceNamespace + ".servicebus.windows.net/" + entityPath;
var endocedResourceUri = encodeURIComponent(uri);
var t0 = new Date(1970, 1, 1, 0, 0, 0, 0);
var t1 = new Date();
var expireInSeconds = + (31*24*3600) + 3600 + (((t1.getTime() - t0.getTime()) / 1000) | 0);
var plainSignature = utf8_encode(endocedResourceUri + "\n" + expireInSeconds);
var hash = CryptoJS.HmacSHA256(plainSignature, m_SasKey);
var base64HashValue = CryptoJS.enc.Base64.stringify(hash);
var token = "SharedAccessSignature sr=" + endocedResourceUri + "&sig=" +
encodeURIComponent(base64HashValue) + "&se=" + expireInSeconds + "&skn=" + m_SasKeyName;
return token;
};
function sendMessage(entityPath, deviceName, body, contentType, callback) {
var securityToken = getToken(entityPath);
var entityUri = "https://" + m_ServiceNamespace + ".servicebus.windows.net/" + entityPath;
var sendUri = entityUri + "/publishers/" + deviceName + "/messages/";
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", sendUri, true);
xmlHttpRequest.setRequestHeader('Content-Type', contentType);
xmlHttpRequest.setRequestHeader("Authorization", securityToken);
xmlHttpRequest.onreadystatechange = function () {
if (this.readyState == 4) {
var messagingResult;
// Expects HTTP-201 (Created) when the
// message is entered in the queue / topic.
if (this.status == 201) {
messagingResult = new MessagingResult("Success", this.status, null, this.response);
}
else {
messagingResult = new MessagingResult("Failure", this.status, null, this.response);
}
callback(messagingResult);
}
};
xmlHttpRequest.send(body);
return securityToken;
};
function utf8_encode(argString) {
// discuss at: http://phpjs.org/functions/utf8_encode/
// original by: Webtoolkit.info (http://www.webtoolkit.info/)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: sowberry
// improved by: Jack
// improved by: Yves Sucaet
// improved by: kirilloid
// bugfixed by: Onno Marsman
// bugfixed by: Onno Marsman
// bugfixed by: Ulrich
// bugfixed by: Rafal Kukawski
// bugfixed by: kirilloid
// example 1: utf8_encode('Kevin van Zonneveld');
// returns 1: 'Kevin van Zonneveld'
if (argString === null || typeof argString === 'undefined') {
return '';
}
// .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var string = (argString + '');
var utftext = '',
start, end, stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode(
(c1 >> 6) | 192, (c1 & 63) | 128
);
} else if ((c1 & 0xF800) != 0xD800) {
enc = String.fromCharCode(
(c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
} else {
// surrogate pairs
if ((c1 & 0xFC00) != 0xD800) {
throw new RangeError('Unmatched trail surrogate at ' + n);
}
var c2 = string.charCodeAt(++n);
if ((c2 & 0xFC00) != 0xDC00) {
throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
}
c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
enc = String.fromCharCode(
(c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
}
if (enc !== null) {
if (end > start) {
utftext += string.slice(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.slice(start, stringl);
}
return utftext;
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment