带有 Azure B2C 的 Blazor Web Assembly 应用程序总是在加载页面后立即尝试进行身份验证

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

我正在将对 Azure AD B2C 的支持添加到 Blazor WebAssembly 应用程序,我按照此处的说明进行操作 https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/hosted-with-azure-active-directory-b2c?view=aspnetcore-3.1#client-app-configuration

但是,应用程序总是在我加载页面后立即尝试进行身份验证, 这不允许站点的 public 匿名部分。 这个问题有什么解决办法吗?

默认的httpClient需要授权,所以即使打电话查看某人是否获得授权也会导致代码提示用户登录开始。

所以为了解决这个问题,在 Program.cs 文件(在客户端项目中)中,我创建了一个 httpClient 允许 匿名请求

// This allows anonymous requests
// See: https://docs.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));

这个例子应该有帮助: https://github.com/ADefWebserver/SyncfusionHelpDeskClient/blob/main/Client/Pages/Index.razor

它调用 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();
    }
}