Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriden HandleUnauthorizedAsync not being called .NET Core

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

like image 597
Tophat Gordon Avatar asked May 16 '17 20:05

Tophat Gordon


People also ask

How do I override an authorized attribute in .NET Core?

We have code base ready, we need to implement the wrapper class to handle the API request. Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method.

How do you handle exceptions globally in .NET Core?

The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.

How do I Authorize my NET Core?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.

How do I bypass authorization in Web API?

If you want to allow anonymous access you can use the [AllowAnonymous] attribute. This will block access to all methods when a user is not authorized, except the GetData() method which can be called anonymously.


1 Answers

in my case the reason for my handler not being called was that my AuthenticationScheme wasn't selected as default. I had to include it in my Authorize attribute like this:

[HttpGet]
[Authorize(AuthenticationSchemes= "MyAuth")]
public IEnumerable<string> Get()
{
    ...
}

btw: the AutomaticChallenge option seems to have been removed in .net core 2.0

like image 160
user1859022 Avatar answered Sep 24 '22 13:09

user1859022