ASP.NET Core 3.1 how to return 401 Unauthorized instead of Challenge with Azure AD B2C

Viewed 1512

In my API controller, I want the [Authorize] attribute to return 401 Unauthorized instead of forcing an Azure AD B2C sign-in challenge and return that response to my front-end (making ajax calls to the API).

The challenge redirect doesn't work because of the Azure CORS policy. I have found multiple answers, non of which seem to work (401 is not returned, it still tries to redirect to the Azure B2C challenge).

API Controller:

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class HierarchyController : ControllerBase
// ...

Here's my current Startup.ConfigureServices code:

// ...
services.Configure<AzureADB2COptions>(opt => 
            Configuration.GetSection("AzureAdB2C").Bind(opt));

services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(opt => Configuration.Bind("AzureAdB2C", opt))
            .AddCookie(opt =>
            {
                opt.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = ctx =>
                    {
                        ctx.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    }
                };
            });

I have also tried using:

services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.Headers["Location"] = context.RedirectUri;
                context.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
        });

And in both cases switching OnRedirectToLogin up with OnRedirectToAccessDenied. None of those work. Breakpoints inside those events are never hit and, after doing an unauthorized API call, I get this error:

Access to XMLHttpRequest at <MY_B2C_ADDR> (redirected from 'https://localhost:44394/api/Hierarchy') from origin 'https://localhost:44394' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Edit: ConfigureServices

// ...
app.UseRouting(); 

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
      endpoints.MapControllerRoute(
           name: "default",
           pattern: "{controller}/{action=Index}/{id?}");
});
1 Answers

For anyone (or me) reading in the future - I have solved the issue. In ConfigureServices do:

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = AzureADB2CDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignOutScheme = AzureADB2CDefaults.AuthenticationScheme;
        })
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options))
            .AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }

                        return Task.FromResult(0);
                    }
                };
            });
Related