I have Web API with OWIN Authentication in Web MVC.
I'm using <authentication>
in Web.Config for my Web MVC so it's redirecting to login page.
<authentication mode="Forms">
<forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All"
timeout="43200" path="/" requireSSL="false" slidingExpiration="true" />
</authentication>
I'm using [System.Web.Http.Authorize]
attribute to authorize my Web API. But somehow, the API redirecting to login page same like my MVC app because of above configuration.
what I want to do is keep redirecting function for the Web MVC but returning 401 for Web API. How can I achieve this? should I create a custom authorization attribute for Web API?
--EDIT--
I found the answer from this post SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi
So I just add a few lines into my Startup.cs
. I had all my controllers configured with a "api" prefix route.
HttpConfiguration config = new HttpConfiguration();
//..some OWIN configuration
app.Map("/api", inner =>
{
inner.UseWebApi(config);
});
make sure you put app.Map()
after Web Api Configuration lines. Otherwise, it will give error to MVC application.
In .NET Core I have solved it like this, Startup.cs:
Create a custom
AuthorizeAttribute
:If you in the future skip the web.config stuff and use owin to setup your authentication, you could in your
Startup.cs
do:This is what worked for me.
Creating a custom attribute:
Using the attribute in your controller:
Here are just overriding the HandleUnauthorizedRequest method of the AuthorizeAttribute. So, instead of sending a redirect (304) to the login page, we send Forbidden(403) HTTP status code.
In order to change the way IIS behaves based on a convention defined by URL, you want to branch your OWIN pipeline. You can do this by using
IApplicationBuilder.Map
. Assuming a staticconfig
:The
Map
method branches the pipeline to theHandleWebApiRequests
method based on an URL that begins with"/api"
.This should cause 401 errors to behave like they are supposed to and simply return 401 with no redirect.
I needed to configure the StatusCodePage middleware to avoid redirection