Created
November 2, 2023 21:19
-
-
Save indriApollo/dec59b7b74161e51a13649ffa2011fd4 to your computer and use it in GitHub Desktop.
Azure MQTT
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
using System.Security.Cryptography.X509Certificates; | |
using MQTTnet; | |
using MQTTnet.Client; | |
const string eventGridUrl = "<resource>.ts.eventgrid.azure.net"; | |
const string deviceId = "test-device-01"; | |
const string clientCertFile = "test-device-01.crt"; | |
const string clientKetFile = "test-device-01.key"; | |
var cert = X509Certificate2.CreateFromPemFile(clientCertFile, clientKetFile); | |
var mqttFactory = new MqttFactory(); | |
using var mqttClient = mqttFactory.CreateMqttClient(); | |
var mqttClientOptions = new MqttClientOptionsBuilder() | |
.WithTcpServer(eventGridUrl, 8883) | |
.WithTlsOptions(o => o.WithClientCertificates(new [] | |
{ | |
cert | |
})) | |
.WithClientId(deviceId) | |
.WithCredentials(deviceId) | |
.Build(); | |
using var timeout = new CancellationTokenSource(5000); | |
await mqttClient.ConnectAsync(mqttClientOptions, timeout.Token); | |
Console.WriteLine("The MQTT client is connected."); | |
await mqttClient.DisconnectAsync(); |
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
using System.Globalization; | |
using System.Net; | |
using System.Security.Cryptography; | |
using System.Text; | |
using MQTTnet; | |
using MQTTnet.Client; | |
const string iotHubUri = "<hub>.azure-devices.net"; | |
const string deviceId = "<id>"; | |
const string accessKey = "<key>"; | |
var username = $"{iotHubUri}/{deviceId}/?api-version=2021-04-12"; | |
var password = GenerateSasToken($"{iotHubUri}/devices/{deviceId}", accessKey); | |
var mqttFactory = new MqttFactory(); | |
using var mqttClient = mqttFactory.CreateMqttClient(); | |
var mqttClientOptions = new MqttClientOptionsBuilder() | |
.WithTcpServer(iotHubUri, 8883) | |
.WithTlsOptions(o => o.UseTls()) | |
.WithClientId(deviceId) | |
.WithCredentials(username, password) | |
.Build(); | |
using var timeout = new CancellationTokenSource(5000); | |
await mqttClient.ConnectAsync(mqttClientOptions, timeout.Token); | |
Console.WriteLine("The MQTT client is connected."); | |
await mqttClient.DisconnectAsync(); | |
return; | |
static string GenerateSasToken(string resourceUri, string key, string? policyName = null, int expiryInSeconds = 3600) | |
{ | |
var fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1); | |
var expiry = Convert.ToString((int)fromEpochStart.TotalSeconds + expiryInSeconds); | |
var stringToSign = WebUtility.UrlEncode(resourceUri) + "\n" + expiry; | |
var hmac = new HMACSHA256(Convert.FromBase64String(key)); | |
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); | |
var token = string.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", | |
WebUtility.UrlEncode(resourceUri), WebUtility.UrlEncode(signature), expiry); | |
if (!string.IsNullOrEmpty(policyName)) | |
{ | |
token += "&skn=" + policyName; | |
} | |
return token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment