c# - 如何为存储帐户列表启用 AAD 身份验证?

标签 c# azure .net-core azure-storage-account

我正在关注this用于列出我的订阅中的所有存储帐户的教程。以前我使用过 Microsoft.Azure.Management.Fluent,但现在已弃用,因此这就是切换到 Microsoft 建议的新方法的原因。我的 Microsoft.Azure.Management.Fluent 没有任何问题,但现在我无法针对稍后用作 ArmClient< 的输入的 DefaultAzureCredential 进行身份验证。我为我的应用服务打开了托管身份,其中包含调用列出存储帐户的函数的代码,但仍然不起作用。我花了最后两天的时间寻找正确的权限以及如何设置它们,但失败了。有人在云中使用过此功能吗?您做了什么使其发挥作用?

最佳答案

我尝试在我的环境中重现相同的内容并得到以下结果:

我使用相同的代码创建了一个 Web 应用程序,并将其成功发布到 Azure,如下所示:

enter image description here

当我检查 Portal 时,在 Azure Web App 中创建的 webjob 具有相同名称,如下所示:

enter image description here

现在,我通过单击 Run 运行上述 webjob,其中状态更改为 Running,如下所示:

enter image description here

当我从上面的屏幕检查日志选项卡时,我得到了 AuthorizationFailed 错误响应,如下所示:

enter image description here

Note that, DefaultAzureCredential will automatically detect authentication method based on your app's configuration. If you enabled system-managed identity, make sure to assign proper RBAC role to it.

要列出订阅中的存储帐户,您可以将 Storage Blob Data ReaderReader 角色分配给订阅下的托管身份,如下所示:

转到 Azure 门户 -> 应用服务 -> 您的应用服务 -> 身份 -> Azure 角色分配

enter image description here

我选择了 Storage Blob Data Reader 角色,其范围为 订阅,如下所示:

enter image description here

几分钟后,角色成功分配给托管身份,如下所示:

enter image description here

当我现在运行 webjob 时,我得到了带有 Succeeded 消息的响应,如下所示:

enter image description here

要通过 Visual Studio 从本地环境运行相同代码,请使用 DefaultAzureCredential 用作身份验证方法的有效用户帐户登录.

就我而言,我运行了 az login 命令并使用 admin 帐户登录,如下所示:

enter image description here

当我现在运行相同的代码来列出存储帐户时,我成功收到了资源 ID 的响应,如下所示:

using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Storage;

TokenCredential cred = new DefaultAzureCredential();

ArmClient client = new ArmClient(cred);

string subscriptionId = "9c80bd38-bcc9-4ccb-8afe-xxxxxxxxxx";
ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId);
SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId);

await foreach (StorageAccountResource item in subscriptionResource.GetStorageAccountsAsync())
{

    StorageAccountData resourceData = item.Data;
    // for demo we just print out the id
    Console.WriteLine($"Succeeded on id: {resourceData.Id}");
}

Console.WriteLine($"Succeeded");

回应:

enter image description here

引用: How to authenticate .NET applications with Azure services | Microsoft

关于c# - 如何为存储帐户列表启用 AAD 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75659937/

相关文章:

c# - 如何添加 ACL 规则而不替换现有规则?

c# - 限制加密中使用的字符

git - Azure DevOps 构建中出现 "No url found for submodule path in .gitmodules"错误

c# - 在 aws eb 上存储 asp.net core 2 的连接字符串

c# - 在不同的 .NET 框架之间共享记录器

c# - 我怎样才能实现我自己的外部类型?

c# - 使用 C# 4.0 在 3 层 winform 应用程序中存储连接字符串的位置

azure - 从 json 请求正文中获取值并将其存储在 Azure API 管理中的变量中

c# - Azure 文件存储 云文件

c# - .NET Core 不支持 BeginInvoke? (PlatformNotSupported 异常)