Powershell访问正常,但AzureCliCredential失败,显示“主体X未授权”

t5fffqht  于 2023-06-30  发布在  Shell
关注(0)|答案(1)|浏览(98)

在VS Code中的多语言笔记本中,在

az login --tenant xyz

我可以

az iot hub device-twin show --hub-name 'hub1' --device-id 'John' --query 'properties.desired' --output json --subscription 'sub1'

太棒了
可悲的是,当我试图使用C#来获取双胞胎时,我无法让AzureCredential的任何提供程序工作。例如:

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

失败:
错误:Microsoft.Azure.Devices.Common.Exceptions.UnauthorizedException:{“Message”:“ErrorCode:IotHubUnauthorized; Principal @.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”}
在尝试使用InteractiveBrowserCredential时出现相同的错误。
使用连接字符串的工作原理:

var rm = RegistryManager.CreateFromConnectionString("HostName=hub1.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=abc=");
            
var twin = await rm.GetTwinAsync(deviceId); // This works

问:我可以使用AzureCliCredential/InteractiveBrowserCredential使用我的个人帐户向Azure进行身份验证吗?
包含的库包括:

#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;
62lalag4

62lalag41#

错误:Microsoft. Azure. Devices. Common. Exceptions. UnauthorizedException:{"Message ":" ErrorCode:IotHubUnauthorized; Principal@. 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 "}
当您没有适当的角色来使用凭据访问设备ID时,会发生上述错误。
你需要为你的用户使用**IoT Hub Data Contributor**role,你可以使用Defaultazurecredential来使用c#获取双胞胎。

    • 角色:**

对Defaultazuzurecredential使用相同的代码,并成功执行。

    • 代码:**
using Azure.Identity;
 using Microsoft.Azure.Devices;
    
    
    var hub = "<your-hub-name>.azure-devices.net";
    var deviceId = "<your-device-name>";
    
    var credential = new DefaultAzureCredential();
    var rm = RegistryManager.Create(hub, credential);
    var twin = await rm.GetTwinAsync(deviceId);
    Console.WriteLine(twin.DeviceScope);
    • 输出:**
{
  "$metadata": {
    "$lastUpdated": "2021-08-11T05:22:12.3717129Z"
  },
  "$version": 1
}

相关问题