Overriden HandleUnauthorizedAsync not being called .NET Core

Viewed 5138

I have implemented my own custom authentication middleware and handler, and configured them in the app startup. This is all working fine.

In my custom auth handler where I have overriden HandleAuthenticateAsync() to do my own custom auth, I have also overriden HandleUnauthorizedAsync() in order to redirect the user to the login page, but this isn't getting called.

The browser is receiving a 401 (Unauthorized) in the response. I was expecting my HandleUnauthorizedAsync() to be called.

Am I not understanding the pipeline correctly here?

Thanks

4 Answers

user1859022's helped in my case, but I didn't want to type a name of my scheme for every [Authorize]. And specifying DefaultAuthenticateScheme didn't work at first as well.

My mistake was kinda stupid. I had both app.UseAuthorization() and app.UseAuthentication() and of course the order was wrong. The correct version is

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();

        app.UseHttpsRedirection();

        app.UseRouting();

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

        app.UseEndpoints(endpoints => endpoints.MapControllers());
}

So make sure that UseAuthentication is called before UseAuthorization.

The above solution did work for me as well I was able to improve on it with following code segment, then there is no need to specify the authentication scheme name in the [Authorize] attribute. It is important to call the AddAuthentication method before AddMvc.

public void ConfigureServices(IServiceCollection services)
{
    //must be placed before the AddMvc call
    services.AddAuthentication(options => 
                {                    
                    options.DefaultAuthenticateScheme = "MyAuth";
                    options.DefaultChallengeScheme = "MyAuth";
                })
                .AddCustomAuth(o => { });
    
    services.AddMvc();
}

Mihail's answer solved it for me, but just so that it's clear:

If your request is hitting ChallengeAsync but not HandleAuthenticateAsync or AuthenticateAsync

Then check your ordering:

  1. app.UseAuthentication();
  2. app.UseAuthorization();
Related