Search code examples
c#asp.net-coreazure-ad-b2cazure-ad-msalazure-authentication

Authentication.AzureADB2C.UI - How to customize Error Page - .Net Core 3.1


I have a project that we are using the package Microsoft.AspNetCore.Authentication.AzureADB2C.UI to authenticate with Azure AD B2C. Some times, if a session expire or a user tries to login directly from the Azure AD B2C sign in page, this error page [Error Page] will appear(https://github.com/dotnet/aspnetcore/blob/master/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/Areas/AzureADB2C/Pages/Account/Error.cshtml): Error page

However, I'd like to customize this page, but I couldn't figure out how to do that.

I'm already customizing the AzureADB2C Controller to use a customized sign out page, by replacing the Sign Out method. However, there isn't a "Error" method in this controller.

Can someone show me a direction to go?

Thank you

UPDATE

In addition to the fix provided, I also modified the code below to force the user to be redirect to the Sign In page again, if a Remote Failure happens. I noticed this solves most of the times that someone would receive that error:

`public class AzureADB2COpenIdConnectOptionsConfigurator : IConfigureNamedOptions<OpenIdConnectOptions>`

(...)

public void Configure(string name, OpenIdConnectOptions options)
        {
           (...)
            options.Events.OnRemoteFailure = WrapOpenIdConnectEvent(options.Events.OnRemoteFailure, OnRemoteFailture);
           (...)
}

  private Task OnRemoteFailture(RemoteFailureContext context)
        {
            // Log exception
            _logger.LogInformation("Azure - Failure Sign In - ContextFailure: " + context.Failure.ToString());

            // Redirect user to SignIn, most of the times, the user will be simply logged in and won't see the developer page exception anymore
            context.Response.Redirect("/AzureADB2C/Account/SignIn");

            context.HandleResponse();

            return Task.CompletedTask;
        }


Solution

  • if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Account/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    
        //Put this  method:
        app.UseRewriter(new RewriteOptions().Add(context =>
        {
            if (context.HttpContext.Request.Path == "/AzureADB2C/Account/SignedOut")
            {
                context.HttpContext.Response.Redirect("/Home/SignedOut");
            }
        }));
        app.UseHsts();
    }