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?}");
});