Created
October 13, 2016 05:22
-
-
Save jongio/5a6ddaa76b939db31e7a01faf205139d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var crypto = require('crypto'); | |
| var https = require('https'); | |
| var generateSasToken = function (resourceUri, signingKey, policyName, expiresInMins) { | |
| resourceUri = encodeURIComponent(resourceUri.toLowerCase()).toLowerCase(); | |
| // Convert mins to seconds and get expires code | |
| var expires = (Date.now() / 1000) + expiresInMins * 60; | |
| expires = Math.ceil(expires); | |
| // Set the string to sign | |
| var toSign = resourceUri + '\n' + expires; | |
| // Get hash | |
| var hmacHash = getHmacHash(signingKey, toSign); | |
| var base64UriEncoded = encodeURIComponent(hmacHash); | |
| // construct autorization string | |
| var token = "SharedAccessSignature sr=" + resourceUri + "&sig=" + base64UriEncoded + "&se=" + expires; | |
| if (policyName) | |
| token += "&skn=" + policyName; | |
| return token; | |
| }; | |
| function getHmacHash(key, stringToSign) { | |
| var hmac = crypto.createHmac('sha256', new Buffer(key, 'base64')); | |
| hmac.update(stringToSign); | |
| return hmac.digest('base64'); | |
| } | |
| var sendMessage = function (message) { | |
| var apiVersion = '2016-02-03'; | |
| var hubName = 'jongiothub.azure-devices.net'; | |
| var deviceId = 'device148'; | |
| var devicePath = '/devices/' + deviceId; | |
| var hubDevicePath = hubName + devicePath; | |
| var deviceEventsPath = devicePath + '/messages/events?api-version=' + apiVersion; | |
| var deviceKey = ''; | |
| var token = generateSasToken(hubDevicePath, deviceKey, null, 60); | |
| var options = { | |
| hostname: hubName, | |
| port: 443, | |
| path: deviceEventsPath, | |
| method: 'POST', | |
| headers: { | |
| 'Authorization': token | |
| } | |
| }; | |
| var req = https.request(options, function (res) { | |
| console.log('HTTP Status:' + res.statusCode); | |
| }); | |
| req.write(message); | |
| req.end(); | |
| }; | |
| sendMessage('{"Value": 42}'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment