Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Not Authorized Redirect to Account/Login in ASP.NET Core

I have a set of WebAPI services in a shared library. These are used in an ASP.NET Core MVC Web Site and dedicated server only hosting the WebAPI Services without the MVC component.

Everything works as expected on the MVC Web Site with Unauthorized Requests, I get the 304 redirect to the login page (Account/Login). However when I make an unauthorized request to the WebAPI services, I receive the same 304 redirect to /Account/Login in this case I would like to return the Http 401 Unauthorized result code. I would prefer to not handle this in a custom AuthorizeAttribute but would rather handle at the site level in my Startup class.

like image 292
Kevin Avatar asked Apr 17 '17 16:04

Kevin


1 Answers

I suspect you have registered ASP.NET Core Identity with both your MVC (Views) Part as well as with your WebApi part.

You must separate it and the CookieMiddleware (one registered inside .UseIdentity() call) must only be registered for request to your MVC pages, but not for your WebAPI calls.

You can use the .Map or MapWhen methods (see docs).

// For requests not going to WebAPI controllers
app.MapWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch =>
{
    branch.UseIdentity();
});
like image 154
Tseng Avatar answered Oct 19 '22 17:10

Tseng