【问题标题】:How to Authorize a Managed Identity to access Azure Table Storage using Microsoft.WindowsAzure.Storage.Table.CloudTableClient如何使用 Microsoft.WindowsAzure.Storage.Table.CloudTableClient 授权托管标识访问 Azure 表存储
【发布时间】:2021-12-14 18:01:32
【问题描述】:

我正在使用Microsoft.WindowsAzure.Storage C# 库通过存储凭据访问我的Azure Table Storage 帐户,如下所示。

_CloudStorageAccount = new CloudStorageAccount(
                new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
                azureStorageAccountName, azureStorageAccountKey),
                true
            );
_CloudTableClient = _CloudStorageAccount.CreateCloudTableClient();

不过,微软最近表示,现在可以使用Managed Identities (Authorize access to tables using Azure Active Directory (preview)) 访问 ATS 服务,他们在此处分享了以下代码示例,说明如何使用托管身份创建表:

public static void CreateTable(string accountName, string tableName)
{
    // Construct the table endpoint from the arguments.
    string tableEndpoint = string.Format("https://{0}.table.core.windows.net/",
                                                accountName);

    // Get a token credential and create a service client object for the table.
    TableClient tableClient = new TableClient(new Uri(tableEndpoint), 
                                                tableName, 
                                                new DefaultAzureCredential());

    try
    {
        // Create the table.
        tableClient.Create();

    }
    catch (RequestFailedException e)
    {
        Console.WriteLine("Exception: {0}", e.Message);
    }
}

这很好,但此示例使用 Azure.Data.Tables.TableClient 而不是我当前使用的 Microsoft.WindowsAzure.Storage.Table.CloudTableClient,所以有没有办法使用托管标识显式使用 CloudTableClient 访问 Azure Table Storage 服务?

【问题讨论】:

标签: azure azure-active-directory azure-cosmosdb azure-table-storage azure-managed-identity


【解决方案1】:

您可以使用下面的代码通过 Microsoft.WindowsAzure.Storage.Table.CloudTableClient 使用托管标识在 Azure 表存储中创建一个表

public static async Task createTable(string accountName, string tableName)
{
            string tableEndpoint = string.Format("https://{0}.table.core.windows.net/",accountName);
            var token = await new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/");
            var tokenCredential = new TokenCredential(token);
            var storageCredentials = new StorageCredentials(tokenCredential);
            var tableClient = new CloudTableClient(new Uri(tableEndpoint), storageCredentials);
            var table = tableClient.GetTableReference(tableName);
            table.CreateIfNotExistsAsync().Wait();
}

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2019-10-10
    • 2021-04-07
    • 2021-11-08
    • 2021-04-07
    • 1970-01-01
    • 2021-02-20
    • 2020-08-31
    相关资源
    最近更新 更多