CarComp
CarComp

Reputation: 2026

Why do my Admin controllers trigger OnRemoteFailure in ConfigureOpenIdConnectOptions when using custom authentication policies?

I am configuring authentication and authorization in an ASP.NET Core application using both OpenIdConnect and Microsoft Identity. The goal is to make the frontend controllers for my site use the OpenIdConnect (IdentityServer4) and the admin controllers use AzureAd. Here's a summary of my setup:

In Startup.cs, I have configured authentication and authorization as follows:

services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureOpenIdConnectOptions(); 
services.AddSingleton<IConfigureOptions<MicrosoftIdentityOptions>, ConfigureAzureAdConnectOptions>();

AuthenticationBuilder authBuilder = services.AddAuthentication(options =>
{
    options.DefaultScheme = "IS4Cookies";
    options.DefaultChallengeScheme = "SigmaSSO";
});
authBuilder.AddCookie("IS4Cookies"); // Add a cookie handler
authBuilder.AddOpenIdConnect("SigmaSSO", null);
authBuilder.AddMicrosoftIdentityWebApp(Configuration, "AzureAd", "EntraIdOIDC", "EntraId", true);

services.AddAuthorization(options =>
{
    options.AddPolicy("AdminSection", policy =>
    {
        policy.AddAuthenticationSchemes("EntraIdOIDC");
        policy.RequireAuthenticatedUser();
        policy.RequireRole(new List<string>{"PlusAdminUser"});
    });

    options.AddPolicy("FrontEnd", policy =>
    {
        policy.AddAuthenticationSchemes("SigmaSSO");
        policy.RequireAuthenticatedUser();
    });
});

I also have this event configured in ConfigureOpenIdConnectOptions:

options.Events = new OpenIdConnectEvents()
{
    OnRemoteFailure = ctx =>
    {
        ctx.HandleResponse();
        ctx.Response.Redirect("/");
        return Task.FromResult(0);
    }
};

For my controllers, I have the following attributes:

Admin Controllers:

[Area("Admin")]
[Authorize(Policy = "AdminSection")]

Frontend Controllers:

[Area("Admin")]
[Authorize(Policy = "FrontEnd")]

ConfigureAzureAdConnectOptions only contains basic information as such:

options.Instance = "https://login.microsoftonline.com/";
options.Domain = "azure-domain-here";
options.TenantId = "someguid";
options.ClientId = "some-other-guid";
options.CallbackPath = "/signin-oidc";
options.SignInScheme = "AzureCookies";
options.Scope.Add("openid");

The problem I'm encountering is that when I access any of my Admin controllers, the OnRemoteFailure event is triggered from the ConfigureOpenIdConnectOptions class, which causes a redirect to the homepage.

I expect this event to trigger only on OpenID Connect-related failures, but it is happening consistently when accessing admin routes.

Why are my Admin controllers triggering the OnRemoteFailure event from ConfigureOpenIdConnectOptions? How can I prevent this behavior and ensure it only triggers on legitimate OpenID Connect failures?

Additional Information:

Upvotes: 0

Views: 116

Answers (0)

Related Questions