首页 > 解决方案 > 如何使用 Microsoft.WindowsAzure.Storage.Table.CloudTableClient 授权托管标识访问 Azure 表存储

问题描述

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

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

但是,Microsoft 最近表示现在可以使用Managed Identities使用 Azure Active Directory 授权访问表(预览版))访问 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我目前正在使用的,所以有什么方法可以Azure Table Storage使用托管标识显式地访问服务CloudTableClient

标签: azureazure-active-directoryazure-cosmosdbazure-table-storageazure-managed-identity

解决方案


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

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();
}

推荐阅读