Add the hostname of the IoT Hub endpoint (xyz.azure-devices.net) to the Domain field
Click on the Select Certificate button, locate and select the device.pfx created in the first step. Click on the Ok button and enter the password.
If everything goes right, a new entry will appear under the Client Certificates. Every time Best MQTT connects using TLS and the server asks for a client certificate the plugin will send this certificate back to the server.
Note that the TLS Security doesn't work under WebGL!
All MQTT client connecting to an MQTT broker must have a unique clientId. To achieve this, devices should be added to the IoT Hub and device certificates generated dinamically.
staticvoidTryAddDeviceCertificateToDatabase(stringhost,stringpathToCertificate,stringpassword){vardatabase=TLSSecurity.ClientCredentials;// find out whether we already added the device's client certificatevarcerts=database.FindByTargetDomain(host);if(certs==null||certs.Count==0){varstore=newBest.HTTP.SecureProtocol.Org.BouncyCastle.Pkcs.Pkcs12Store(System.IO.File.OpenRead(pathToCertificate),password.ToCharArray());foreach(stringaliasinstore.Aliases){varcertificate=newBest.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Certificate((fromcertinstore.GetCertificateChain(alias)selectnewBest.HTTP.TLSSecurity.Databases.ClientCredentials.BestHTTPTlsCertificate(cert.Certificate.CertificateStructure)).ToArray());varprivateKeyInfo=Best.HTTP.SecureProtocol.Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(store.GetKey(alias).Key);database.Add(host,newBest.HTTP.TLSSecurity.Databases.ClientCredentials.ClientCredential{Certificate=certificate,KeyInfo=privateKeyInfo});}database.Save();}}
And it can be used in the TLSSecurity.OnSetupFinished callback:
TLSSecurity.OnSetupFinished=()=>{TryAddDeviceCertificateToDatabase("xyz.azure-devices.net","<path to the .pfx file>","<password>");};TLSSecurity.Setup();
After succesfully setting up the TLS Security Addon, connecting with Best MQTT requires the following steps:
Use .WithTLS to ensure the plguin tries to connect using TLS.
Use .WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1) as Azure IoT Hub supports MQTT v3.1.1 only.
Use the device name/id as the clientId in the OnConnectPacketBuilder callback (.WithClientID(deviceId) call in the code below).
Use the combination of the host and device id as the username in the OnConnectPacketBuilder callback (.WithUserName($"{client.Options.Host}/{deviceId}") call in the code below).