How can one use an Entra ID account and Azure’s Access Control (AIM) to access Azure resources, in particular, Azure Blob Storage, directly from the browser, without sharing any secrets (which would be insecure).
No connection strings, no SAS, no client secrets, etc.
This use case enables the creation of applications that have no need for a trusted backend, e.g. Azure Functions, as long as you can trust that authenticated users will not misbehave.
However, I have found no documentation on how to achieve this. All available documentation refers to using Azure.Identity’s set of TokenCredentials, but none of this can be used from a browser.
I have created a full step-by-step guide on how to achieve this: https://github.com/rodolfograve/poc-azurestoragefrombrowserwithentraid
For the sake of having the information available here at SO, this is a summary:
- On the resource you want to access, e.g. Azure Storage Account:
- Configure CORS so that your URL is allowed to perform the operations (GET, OPTIONS, PUT, etc.)
- Use AIM to assign roles to the users (Storage Blob Data Reader, Storage Blob Data Contributor, etc.)
- On Entra ID: grant the “Azure Storage -> user_impersonation” permission to the App Registration.
- On the solution:
- Install the Azure.Identity nuget package.
- Install the Azure.Storage.Blobs nuget package (or the API for the Azure resource you want to access).
- Change the MSAL.NET configuration to request access tokens for the resource you intend to use.
- Add class AccessTokenProviderTokenCredential as defined in the code below.
- Use the AccessTokenProviderTokenCredential where the Azure.* API asks for it (see example below for Azure Storage).
IMPORTANT: the code alone won’t do it. You will get hard-to-understand error messages if the configuration of your resources is wrong. E.g. StatusCode 400 if user_impersonation hasn’t been granted on your App Registration.
Example of MSAL.NET configuration for Azure Storage read and write:
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.AdditionalScopesToConsent.Add("https://storage.azure.com/Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read");
options.ProviderOptions.AdditionalScopesToConsent.Add("https://storage.azure.com/Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write");
});
AccessTokenProviderTokenCredential:
/// <summary>
/// Makes it possible to use MSAL to obtain Azure.Identity access tokens
/// </summary>
public class AccessTokenProviderTokenCredential(IAccessTokenProvider accessTokenProvider) : TokenCredential
{
private readonly IAccessTokenProvider AccessTokenProvider = accessTokenProvider ?? throw new ArgumentNullException(nameof(accessTokenProvider));
public override Azure.Core.AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
var accessTokenResult = AccessTokenProvider.RequestAccessToken(new AccessTokenRequestOptions
{
Scopes = requestContext.Scopes
})
.GetAwaiter()
.GetResult();
if (accessTokenResult.TryGetToken(out var accessToken))
{
var result = new Azure.Core.AccessToken(accessToken.Value, accessToken.Expires);
return result;
}
else
{
throw new Exception($"Failed to obtain access token for scopes '{string.Join(",", requestContext.Scopes)}'");
}
}
public async override ValueTask<Azure.Core.AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
var accessTokenResult = await AccessTokenProvider.RequestAccessToken(new AccessTokenRequestOptions
{
Scopes = requestContext.Scopes
}).ConfigureAwait(false);
if (accessTokenResult.TryGetToken(out var accessToken))
{
var result = new Azure.Core.AccessToken(accessToken.Value, accessToken.Expires);
return result;
}
else
{
throw new Exception($"Failed to obtain access token for scopes '{string.Join(",", requestContext.Scopes)}'");
}
}
}
Example of usage for Azure Storage:
[Inject] private IAccessTokenProvider AccessTokenProvider { get; set; } = default!;
private async Task OnSaveToAzureStorageClick()
{
const string storageAccountBlobEndpoint = "https://nameofstorageaccount.blob.core.windows.net/"; // Replace this with the Blob service endpoint for your own Azure Storage Account.
const string blobContainerName = "test";
var credential = new AccessTokenProviderTokenCredential(AccessTokenProvider);
var blobServiceClient = new BlobServiceClient(new Uri(storageAccountBlobEndpoint), credential);
var blobContainerClient = blobServiceClient.GetBlobContainerClient(blobContainerName);
var blobName = Guid.NewGuid().ToString();
await blobContainerClient.UploadBlobAsync(blobName, new BinaryData("Your own content here"));
}