c# - 使用通过 Azure MSI 获取的 token 从 TokenCredential 创建 Azure CloudStorageAccount

标签 c# azure asp.net-core .net-core serilog

我正在尝试使用通过 Azure 上的 MSI 生成的访问 token 创建一个 CloudStorageAccount,以便在 Serilog Azure Blob 存储接收器中使用。我正在获取 token 并使用以下内容创建帐户

var tokenProvider = new AzureTokenProvider();
var token = await tokenProvider.GetAccessTokenAsync("https://storage.azure.com");
var tokenCredential = new TokenCredential(token);
var storageCredential = new StorageCredential(tokenCredential);
var account = new CloudStorageAccount(storageCredential, "accountnamehere", "core.windows.net", true);

然后我将此帐户传递给 Serilog“LoggerConfiguration”

Log.Logger = new LoggerConfiguration()
    //other stuff
    .WriteTo.AzureBlobStorage(new JsonFormatter(), account, //other settings)
    .CreateLogger()

但是,这永远不会写入 blob。我的 Azure 帐户既直接拥有 Contributor,又从组继承 Storage Blob Data Contributor。我正在使用的 Azure VM 也具有此存储帐户的存储 Blob 数据贡献者。但是,在开发中,它使用的凭据是我的。

当我使用帐户 key 时,blob 写入时没有问题,因此我生成 CloudStorageAccount 的方式不正确,或者 Azure 中的权限设置不正确,我是只是不确定是哪一个。

最佳答案

如果您的开发环境中使用您自己的凭据出现此问题,而该凭据没有您正在使用的存储帐户的存储 Blob 数据贡献者角色,请将此角色添加到您的 Azure 帐户,然后重试。根据我的测试,继承角色似乎在这里不起作用。

我已经在我这边进行了测试,这是我的代码:

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Auth;
using Serilog;
using Serilog.Formatting.Json;
using System;

namespace AzureStorageTest
{
    class Program
    {
        static void Main(string[] args)
        {

            var tokenCredential = new TokenCredential("<access token get from my account 
 whcih has the data contributor role of the stroage account that I am using now>");
            var storageCredential = new StorageCredentials(tokenCredential);

            var account = new CloudStorageAccount(storageCredential, "<my storage account name>", "core.windows.net", true);


            Log.Logger = new LoggerConfiguration().WriteTo.AzureBlobStorage(account).CreateLogger();
            Log.Logger.Error("aaaaa");
            Console.ReadKey();
        }
    }
}

检查我的存储帐户,那里有一个日志文件: enter image description here

其内容:

enter image description here

关于c# - 使用通过 Azure MSI 获取的 token 从 TokenCredential 创建 Azure CloudStorageAccount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59746812/

相关文章:

c# - 获取产品 key 、域名、用户名等 Windows 详细信息。

c# - 使用 SWTableViewCell 的表格单元格滑动菜单

ubuntu - 在 .net core 中添加对 webapi 的包引用

asp.net-mvc - 如何在 ASP.NET Core 2.0 中使用 Razor 页面处理 Ajax 请求

c# - ASP.NET Core API 版本控制 - 部分取代以前的方法版本

c# - 与数据库的 SSL 连接

c# - 声明类型的 MethodInfo 相等性

azure - 通过查看 Cosmos DB 指标日志来计算平均 RUN

c# - Azure 类库访问 GetConfigurationSettingValue 与 web.config

Azure 表存储资源管理器查询