Blazor WebAssembly App protected by AD accessing API protected by AD

Trevor Daniel 6 Reputation points

Hoping for some guidance if possible.

I'm new to Blazor and not a huge expert in the AD area either

I have setup an API which is protected by AD and protected my controllers... they throw a 401 if i try and call them in a browser
I have setup a basic Blazor Webassembly app which is protected by AD and lets me login with no error.

But, within the Blazor app, i want to be able to call the API.

Do i need to give access to the Blazor App to use the API in AD?

A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,448 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,082 questions
{count} votes

1 answer

Sort by: Most helpful
  1. singhh-msft 2,431 Reputation points

    @Trevor Daniel , thank you for reaching out to us. To call a protected Web API from Blazor WebAssembly Web App, you will have to perform below steps:

    • Add Scope to your Web API.
    • Enable Implicit grant flow in your Web App.
    • Create custom AuthorizationMessageHandler in Web App for calling your Web API: using Microsoft.AspNetCore.Components;
      using Microsoft.AspNetCore.Components.WebAssembly.Authentication; public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
      public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
      NavigationManager navigationManager)
      : base(provider, navigationManager)
      authorizedUrls: new[] { "https://localhost:44300/" },
      scopes: new[] { "the API app scope" });
    • Add below code to your Web App's Program.cs: public class Program
      public static async Task Main(string[] args)
      var builder = WebAssemblyHostBuilder.CreateDefault(args);
           // register HTTP client to call our own api  
           builder.Services.AddHttpClient("MyAPI", client => client.BaseAddress = new Uri("https://localhost:44300/"))  
           builder.Services.AddMsalAuthentication(options =>  
               builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);  
               options.ProviderOptions.DefaultAccessTokenScopes.Add("<the API app scope>");  
           await builder.Build().RunAsync();  
    • Now, you can call your API: @inject IHttpClientFactory _clientFactory var httpClient = _clientFactory.CreateClient("<the client name you register>");
      await httpClient.GetStringAsync("path");

    Do check out this good answer on Stack overflow for more information. Feel free to reach out for any follow-up questions.


    Please "Accept the answer" and upvote if the information helped you. This will help us and others in the community as well.

    0 comments No comments