@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)
{
ConfigureHandler(
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);
builder.RootComponents.Add<App>("app");
}builder.Services.AddScoped<CustomAuthorizationMessageHandler>(); // register HTTP client to call our own api builder.Services.AddHttpClient("MyAPI", client => client.BaseAddress = new Uri("https://localhost:44300/")) .AddHttpMessageHandler<CustomAuthorizationMessageHandler>(); builder.Services.AddMsalAuthentication(options => { builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication); options.ProviderOptions.DefaultAccessTokenScopes.Add("<the API app scope>"); options.ProviderOptions.AdditionalScopesToConsent.Add("https://graph.microsoft.com/User.Read"); }); 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.