Search code examples
c#azurepowershellazure-storage-accountsas-token

Azure SAS Token


I just upgraded Visual Studio to 2022 and discovered that Cloud Connector is no longer part of VS. We used to generate SAS Tokens for our IoT devices from VS, and they took this form:

SharedAccessSignature sr=azure-devices.net%2Fdevices%2F<DeviceID>&sig=<VS sig string>%3D&se=1979665819

I figure 'No problem. I'll just make one with PowerShell'. It looks different and does not work. My devices gets "unexpectedly disconnected". I used this code:

$context = (Get-AzStorageAccount -ResourceGroupName $resourceGroup -AccountName $storageAccount).context
New-AzStorageAccountSASToken -Context $context 
                             -Service Table,Queue 
                             -ResourceType Service,Container,Object 
                             -Permission racwdlup 
                             -ExpiryTime $tenYears

It generates a token that looks like this:

sv=2021-06-08&ss=qt&srt=sco&se=2032-09-29T15%3A28%3A56Z&sp=rwdlacup&sig=<PS sig string>

I figured I could just substitute the PS sig string in where the VS sig string would go, but that didn't work. Pasting the entire PS SAS token into the device's SAS Token field doesn't work either. Unfortunately I don't have access to any error messages, only what the device puts in the log: MQTT Disconnected (unexpected). If I output MQTT STATUS it has a value of 4 which according to the manual simply means disconnected.

I suspect my issue is that the old VS tokens were container level tokens whereas the PowerShell command generates an account level token. Is there anyway to make the correct token with PowerShell or C#?


Solution

  • Turns out there's already a PowerShell command to do this: New-AzIotHubSasToken

    New-AzIotHubSasToken -ResourceGroupName "myResourceGroup" 
                         -IotHubName "myIoTHub" 
                         -DeviceId "myDevice"
    
    SharedAccessSignature sr=myIoTHub.azure-devices.net%2Fdevices%2FmyDevice
                         &sig=<signature>
                         &se=<epiry>