I am trying to use the DefaultAzureCredentials to authenticate the TableServiceClient for inserting entities into Azure Table Storage.
This is the code in my Startup.cs:
DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions
{
Diagnostics =
{
LoggedHeaderNames = { ...},
IsLoggingContentEnabled = true,
IsTelemetryEnabled = true,
IsAccountIdentifierLoggingEnabled = true
},
ExcludeAzurePowerShellCredential = true,
ExcludeSharedTokenCacheCredential = true,
ExcludeVisualStudioCredential = true,
ExcludeWorkloadIdentityCredential = true,
ExcludeEnvironmentCredential = true,
ExcludeManagedIdentityCredential = true,
ExcludeAzureDeveloperCliCredential = true,
ExcludeInteractiveBrowserCredential = true,
};
services.AddSingleton(new TableServiceClient(
endpoint: new Uri(Configuration.GetValue<string>("AzureTableStorage:Uri")),
tokenCredential: new DefaultAzureCredential(options)));
The logs from the authentication look like this:
[Informational] Azure-Identity: DefaultAzureCredential credential selected: Azure.Identity.AzureCliCredential
[Informational] Azure-Identity: DefaultAzureCredential.GetToken succeeded. Scopes: [ https://storage.azure.com/.default ]
I can add entities to the tables using the Azure CLI:
az storage entity insert --account-name oodledev --account-key xxxxx --table-name purchaseorder --entity PartitionKey=3 RowKey=CA, username=Sam
But when I try testing my C# application that inserts table rows, I get an exception:
tableClient.SubmitTransactionAsync(transactionActions);
Exception thrown: 'Azure.Data.Tables.TableTransactionFailedException' in System.Private.CoreLib.dll: '0: this request is not authorized to perform this operation using this permission.
RequestId:f14fc64e-8002-0038-28f3-59a7ea000000
Time:2024-02-07T18:26:01.3577039Z
The index of the entity that caused the error can be found in FailedTransactionActionIndex.
Status: 403 (Forbidden)
ErrorCode: AuthorizationPermissionMismatch
Why can I insert rows from the CLI, but not from the C# application?
I figured it out. I needed to add the Storage Table Data Contributor role for my user on Azure. As @gaurav-mantri pointed out, the CLI uses the account name and key so it does not need that particular role in order to add items to Azure Tables.