简体   繁体   中英

How to Authorize a Managed Identity to access Azure Table Storage using Microsoft.WindowsAzure.Storage.Table.CloudTableClient

I was using the Microsoft.WindowsAzure.Storage C# library to access my Azure Table Storage account using storage credentials as follows.

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

However, Microsoft lately stated that it is now available to access the ATS service using Managed Identities ( Authorize access to tables using Azure Active Directory (preview) ) and they shared the following code example here on how to create the table using Managed Identity:

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

This is fine but this example uses the Azure.Data.Tables.TableClient instead of the Microsoft.WindowsAzure.Storage.Table.CloudTableClient that I'm currently using, so is there any way to access the Azure Table Storage service using Managed Identity explicitly using the CloudTableClient ?

You can use the below code to create a table in Azure Table Storage using Managed Identity with 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM