Skip to content

Instantly share code, notes, and snippets.

@WilliamBerryiii
Last active May 2, 2019 01:40
Show Gist options
  • Save WilliamBerryiii/7a730fbc364fc2b75498746fba5099b9 to your computer and use it in GitHub Desktop.
Save WilliamBerryiii/7a730fbc364fc2b75498746fba5099b9 to your computer and use it in GitHub Desktop.
Using x509 Client Certificates with Azure IoT Protocol Gateway with Node

Instructions for local debug

  • Download and install the Azure Storage Emulator

  • Start the emulator from the Start Menu

  • Add 127.0.0.1 protocol-gateway.contoso.com to your windows hosts file: C:\Windows\System32\drivers\etc\hosts

  • git clone https://github.com/Azure/azure-iot-protocol-gateway

  • Right Click Visual Studio and select Run As Administrator

  • Open the Protocol Gateway Solution

  • Modify the VS Solution host\ProtocolGateway.Host.Console\appSettings.config.user file with your IoT Hub Connection String

  • Run the Solution

  • Create a directory for the Node project

  • Copy the other files in this gist to the project directory

  • run npm install

Open an Adminstrative Powershell Terminal

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname orin.windowsitpro.internal

Assign the thumbprint from the previous command to a variable

$thumbprint = {the return value of the previous command}

Create a password for the cert

$pwd = ConvertTo-SecureString -String "{secure_password}" -Force -AsPlainText

Export the certificate

Export-PfxCertificate -cert "cert:\localMachine\my\$thumbprint" -FilePath c:\temp\cert.pfx -Password $pwd

Open Bash in the Windows Subsystem for Linux and type the following commands

  • cd /mnt/c/temp

  • openssl pkcs12 -in cert.pfx -nocerts -out key.pem -nodes

  • openssl pkcs12 -in cert.pfx -nokeys -out cert.pem

  • openssl rsa -in key.pem -out server.key

  • In Windows Explorer copy the cert files to the Node Project source directory

  • Edit the main.js connectionString with your IoT Hub hostname and Url for the running protocol gateway(protocol-gateway.contoso.com).

  • From a terminal in the Node project directory run node main.js

'use strict';
var fs = require('fs');
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var connectionString = "HostName={iot-hub-hostname}.azure-devices.net;DeviceId=devicex509;GatewayHostName=ssl:{protocol-gateway-url}:8883;x509=true"
var certFile = './cert.pem';
var keyFile = './key.pem';
var passphrase = 'pass@word';
var client = Client.fromConnectionString(connectionString, Protocol);
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err.message);
} else {
console.log('Client connected');
client.on('message', function (msg) {
console.log('Id: ' + msg.messageId + ' Body: ' + msg.data);
client.complete(msg, printResultFor('completed'));
});
var sendInterval = setInterval(function () {
var windSpeed = 10 + (Math.random() * 4); // range: [10, 14]
var temperature = 20 + (Math.random() * 10); // range: [20, 30]
var humidity = 60 + (Math.random() * 20); // range: [60, 80]
var data = JSON.stringify({ deviceId: 'devicex509', windSpeed: windSpeed, temperature: temperature, humidity: humidity });
var message = new Message(data);
message.properties.add('temperatureAlert', (temperature > 28) ? 'true' : 'false');
console.log('Sending message: ' + message.getData());
client.sendEvent(message, printResultFor('send'));
}, 2000);
client.on('error', function (err) {
console.error(err.message);
});
client.on('disconnect', function () {
clearInterval(sendInterval);
client.removeAllListeners();
client.open(connectCallback);
});
}
};
var options = {
cert : fs.readFileSync(certFile, 'utf-8').toString(),
key : fs.readFileSync(keyFile, 'utf-8').toString(),
passphrase: passphrase
};
client.setOptions(options);
client.open(connectCallback);
function printResultFor(op) {
return function printResult(err, res) {
if (err) console.log(op + ' error: ' + err.toString());
if (res) console.log(op + ' status: ' + res.constructor.name);
};
}
{
"name": "gm-cert-demo",
"version": "1.0.0",
"description": "",
"main": "main.js",
"dependencies": {
"azure-iot-device": "^1.1.11",
"azure-iot-device-amqp": "^1.1.11",
"azure-iot-device-mqtt": "^1.1.11"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "William Berry @williamberryiii",
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment