How to use MSAL.NET to access Azure resources (Storage, etc.) from the browser (Blazor) using Entra ID auth

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:

  1. On the resource you want to access, e.g. Azure Storage Account:
    1. Configure CORS so that your URL is allowed to perform the operations (GET, OPTIONS, PUT, etc.)
    2. Use AIM to assign roles to the users (Storage Blob Data Reader, Storage Blob Data Contributor, etc.)
  2. On Entra ID: grant the “Azure Storage -> user_impersonation” permission to the App Registration.
  3. On the solution:
    1. Install the Azure.Identity nuget package.
    2. Install the Azure.Storage.Blobs nuget package (or the API for the Azure resource you want to access).
    3. Change the MSAL.NET configuration to request access tokens for the resource you intend to use.
    4. Add class AccessTokenProviderTokenCredential as defined in the code below.
    5. 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"));
    }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật