Azure IoT Hub – Generating & using SAS tokens for a device

Today we’ll talk about two connection flows you can do with an IoT setup when using keys. An alternative might be to use certificates, but I won’t cover that one today.

When talking about keys, there are two common patterns ;

one where the IoT device has a symmetric key (used to generate SAS tokens)

another where the IoT device is only provided with the SAS token (which is generated by another service)

Flow – Symmetric Key

The first flow is the most common one… Here we save the symmetric key on the device. The device then uses this key to generate SAS tokens. These SAS tokens are then used to connect to the Azure IoT Hub and send messages.

The advantage of this setup is the easy-of-deployment. The flip-side of the coin is that if a device gets compromised, the attacker can then keep on generating SAS tokens (until the device is disabled or the keys regenerated).

Another flow is to only provide the device with SAS tokens and -not- to save the symmetric key on the device. For this to work, we’ll need an intermediate system (here called “Secure Server”) which will generate/provide the SAS token to the device. Here you need to ensure that there is already an authentication flow (separate from the IoT Hub flow) present between the device & the “secure server”.

The advantage of this setup is that in case the device gets compromised, it can only abuse the SAS token for its lifetime (< expiry time). Though the setup requires an intermediate system. For some setups this might be a blessing and for other a curse…

This looks the same as any other SAS creation, though the trick is by adjusitng the “iothubHost” variable ;

var iothubHost =process.env.iothubhostname+“/devices/“+deviceId;

Here we “scope” the SAS token to that single device. If you do not do this, then you generate a SAS token which you can use for ALL your devices. So be careful on implementing this one!

Closing Thoughts

There are various ways of creating the connection from your device towards your IoT Hub. Depending on the context of your project, the flow with the symmetric key or with the SAS token will be more applicable to your case. Though I hope that this posts already clarified the difference between the two flows… 😉

Also a big shout-out to my colleague Mathieu who spent quite some time with me this week getting the “secure server” up & running this week. This post is the result of our symbiosis of our strengths when tackling the challenges we had with this implementation.

Up in the Clouds

Views are my own

The content of this blog will, at all times, portray my own views. At no time will this reflect the views of the organization I am linked to. Neither can the information provided be used as support statement.