Call an API from a Blazor application both protected with Microsoft Identity

Enrico Rossini 176 Reputation points

I'm building an application with Blazor Web Assembly hosted in an ASP.NET Core application. Based from scratch and the boilerplate from Visual Studio, I created the solution.

In another solution I have a web API build with ASP.NET Core (I will call them External API). This application has its own URL and registration in the App Registration in the Azure portal. From Swagger, I can access the APIs and their are protected by the Microsoft authentication.

In the same Tenant ID, I created 2 new app registrations for the Blazor Server and the Blazor WebAssembly. The UI can connect to the Active Directory in order to authenticate the users and the Web Assembly can call the APIs in the server project. For more details about it, see my previous post.

I define the API like the following code

public class CurrenciesController : ControllerBase
    // omit the constructor and the injection
    // AzureAd:Scopes is "User.Read"

    [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<Currency>))]
    public ActionResult GetCurrencies()
        return Ok(repo.GetCurrencies());

Now, my problem is from the Web Assembly to call the External API. In the Program.cs I added


builder.Services.AddHttpClient("Middletier.UI.ServerAPI", client => 
    client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))

builder.Services.AddHttpClient("Middletier.API", client => 
    client.BaseAddress = new Uri("https://localhost:50441"))

builder.Services.AddScoped(sp => 

builder.Services.AddScoped(sp => 

builder.Services.AddMsalAuthentication(options =>
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);

    // this is for the Blazor Server

The MiddletierApiAuthorizationMessageHandler implementation is this one

public class MiddletierApiAuthorizationMessageHandler : AuthorizationMessageHandler
    public MiddletierApiAuthorizationMessageHandler(IAccessTokenProvider provider,
        NavigationManager navigationManager)
        : base(provider, navigationManager)
            authorizedUrls: new[] { "https://localhost:7575" },
            // External API
            scopes: new[] { "api://d3de6da4-xxx/User.Read" });

Then, in a Razor page I added

@inject IHttpClientFactory _clientFactory

@code {
    private Currency[]? currencies;

    protected override async Task OnInitializedAsync()
            var httpClient = _clientFactory.CreateClient("Middletier.API");
            currencies = await httpClient
        catch (AccessTokenNotAvailableException exception)

The call is always 401 (Unauthorized). I added CORS. What do I miss?

A set of technologies in the .NET Framework for building web applications and XML web services.
4,240 questions
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,420 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,848 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce ( 57,891 Reputation points

    If the razor page is a blazor component, then be sure you don't have this issue:

    note: you can add a token tracer extension to the browser, so you can debug the which token is passed, and its scopes and claims. also you can see the token in the browsers network trace. use to debug.

    0 comments No comments