Eduardo Fonseca
Eduardo Fonseca

Reputation: 565

Blazor Web Assembly App with Azure B2C is always trying to authenticate as soon as page is loaded

I am adding support for Azure AD B2C to a Blazor WebAssembly App, I followed the instructions here https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/hosted-with-azure-active-directory-b2c?view=aspnetcore-3.1#client-app-configuration

however, the application is always trying to authenticate as soon as I load the page, which does not allow for a public anonymous section of the site. Is there any solution to this problem?

Upvotes: 1

Views: 370

Answers (1)

Michael Washington
Michael Washington

Reputation: 3075

The default httpClient requires authorization so even making a call to see if a person is authorized causes the code to prompt the user to log in kicks in.

So to get around this, in the Program.cs file (in the Client project), I created a httpClient that allows anonymous requests

// This allows anonymous requests
// See: https://learn.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/additional-scenarios?view=aspnetcore-3.1#unauthenticated-or-unauthorized-web-api-requests-in-an-app-with-a-secure-default-client
            builder.Services.AddHttpClient("ServerAPI.NoAuthenticationClient", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));

This example should help: https://github.com/ADefWebserver/SyncfusionHelpDeskClient/blob/main/Client/Pages/Index.razor

It calls the NoAuthenticationClient httpClient

protected override void OnInitialized()
{
    // Create a httpClient to use for non-authenticated calls
    NoAuthenticationClient =
         ClientFactory.CreateClient(
             "ServerAPI.NoAuthenticationClient");
}

public async Task HandleValidSubmit(EditContext context)
{
    try
    {
        // Save the new Help Desk Ticket

        // Create a new GUID for this Help Desk Ticket
        objHelpDeskTicket.TicketGuid =
            System.Guid.NewGuid().ToString();

        await NoAuthenticationClient.PostAsJsonAsync(
            "SyncfusionHelpDesk", objHelpDeskTicket);

        // Send Email
        HelpDeskEmail objHelpDeskEmail = new HelpDeskEmail();
        objHelpDeskEmail.EmailType = "Help Desk Ticket Created";
        objHelpDeskEmail.EmailAddress = "";
        objHelpDeskEmail.TicketGuid = objHelpDeskTicket.TicketGuid;

        await NoAuthenticationClient.PostAsJsonAsync(
            "Email", objHelpDeskEmail);

        // Clear the form
        objHelpDeskTicket = new HelpDeskTicket();

        // Show the Toast
        ToastContent = "Saved!";
        StateHasChanged();
        await this.ToastObj.Show();

    }
    catch (Exception ex)
    {
        ToastContent = ex.Message;
        StateHasChanged();
        await this.ToastObj.Show();
    }
}

Upvotes: 2

Related Questions