Categories
ASP.NET CORE Azure Blazor

Blazor WASM Call WebAPI Without Access Token

This is for Blazor WASM RC.

So imagine you have a Blazor WASM app, which is a SPA that user might need to sign in to perform some tasks via Web API. Take the case using Azure AD B2C, once we logged in, we’ll have ID and Access Token from Implicit Flow.

By default, the AADB2C template generates the following:

        builder.Services.AddHttpClient("HostedB2C.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
            .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
        // Supply HttpClient instances that include access tokens when making requests to the server project
        builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("HostedB2C.ServerAPI"));

This makes all WebAPIs with Access Token, refresh and such, which is great, secure and convenient.

However, what if there’s a need to call WebAPI as anonymous user?

As of now, there’s no official documentation (should be coming soon). Basically, we can add multiple AddHttpClient for the use case without auth.

To see this in action. In Program.cs, add

        builder.Services.AddHttpClient("HostedB2C.ServerAPI.NoAuth",
                client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));

In the razor component:

@inject IHttpClientFactory ClientFactory

        var client = ClientFactory.CreateClient("HostedB2C.ServerAPI.NoAuth");
        forecasts = await client.GetFromJsonAsync<WeatherForecast[]>("WeatherForecastNA");

There! Now we can call WebAPI using alternative HttpClient (the one without auth).

Leave a Reply

Your email address will not be published. Required fields are marked *