Skip to content

Instantly share code, notes, and snippets.

@rido-min
Created February 3, 2021 02:13
Show Gist options
  • Save rido-min/3d936fc3130ccb498f448c37879f450c to your computer and use it in GitHub Desktop.
Save rido-min/3d936fc3130ccb498f448c37879f450c to your computer and use it in GitHub Desktop.
CallHubAPIs.js
const https = require('https')
const crypto = require('crypto')
const hubUrl = 'xxx.azure-devices.net'
const path = '/devices?api-version=2020-09-30'
const key = 'xxxxxxxxxxxx'
const generateSasToken = (resourceUri, signingKey, policyName, expiresInMins) => {
resourceUri = encodeURIComponent(resourceUri);
// Set expiration in seconds
var expires = (Date.now() / 1000) + expiresInMins * 60;
expires = Math.ceil(expires);
var toSign = resourceUri + '\n' + expires;
// Use crypto
var hmac = crypto.createHmac('sha256', Buffer.from(signingKey, 'base64'));
hmac.update(toSign);
var base64UriEncoded = encodeURIComponent(hmac.digest('base64'));
// Construct authorization string
var token = "SharedAccessSignature sr=" + resourceUri + "&sig="
+ base64UriEncoded + "&se=" + expires;
if (policyName) token += "&skn="+policyName;
return token;
};
const options = {
hostname: hubUrl,
port: 443,
path: path,
method: 'GET',
headers: {
Authorization: generateSasToken(`${hubUrl}/${path}`, key, 'iothubowner', 60)
}
}
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
let body = ''
res.on('data', d => {
//process.stdout.write(d)
body += d
})
res.on('end', () => {
const json = JSON.parse(body)
console.log(json)
})
})
req.on('error', error => {
console.error(error)
})
const data = '{"query":"SELECT deviceId, FROM devices"}'
// req.write(data)
req.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment