In a Polyglot Notebook in VS Code, after
az login --tenant xyz
I can
az iot hub device-twin show --hub-name 'hub1' --device-id 'John' --query 'properties.desired' --output json --subscription 'sub1'
This is great.
Sadly, when trying to get the twin using c# I cannot get any of the AzureCredential`s providers to work. For example:
var hub = "hub1.azure-devices.net";
var deviceId = "John";
var credential = new AzureCliCredential(new AzureCliCredentialOptions { TenantId = "xyz", });
var rm = RegistryManager.Create(hub, credential);
var twin = await rm.GetTwinAsync(deviceId); // This fails
fails with:
Error: Microsoft.Azure.Devices.Common.Exceptions.UnauthorizedException: {"Message":"ErrorCode:IotHubUnauthorized;Principal <edited>@<edited>.com is not authorized for GET on /twins/John due to no assigned permissions","ExceptionMessage":"Tracking ID:abc:0-TimeStamp:06/26/2023 07:44:12"}
The error is the same when trying with InteractiveBrowserCredential
.
Using a connection string works:
var rm = RegistryManager.CreateFromConnectionString("HostName=hub1.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=abc=");
var twin = await rm.GetTwinAsync(deviceId); // This works
Q: Can I authenticate to Azure with my personal account using AzureCliCredential
/ InteractiveBrowserCredential
?
The included libraries are:
#i "nuget:https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json"
#i "nuget:https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json"
#r "nuget:Azure.Identity"
#r "nuget:Microsoft.Extensions.Azure"
#r "nuget:Microsoft.Azure.Devices"
using Azure.Identity;
using Microsoft.Extensions.Azure;
using Microsoft.Azure.Devices;
The above error occurs when you don't have the proper role to access the device id using credentials.
You need to use
IoT Hub Data Contributor
role for your user and you can use the Defaultazurecredential to fetch the twin using c# .Role:
Used the same code with Defaultazurecredential and it executed successfully.
Code:
Output: