Mohammad Fneish
Mohammad Fneish

Reputation: 989

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?

Upvotes: 2

Views: 6692

Answers (1)

RamaraoAdapa
RamaraoAdapa

Reputation: 3137

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

Upvotes: 1

Related Questions