I have a web API with OWIN authentication in web MVC. I use <authentication> in Web.Config for my web MVC, so it redirects to the login page.
<authentication mode="Forms"> <forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All" timeout="43200" path="/" requireSSL="false" slidingExpiration="true" /> </authentication>
I use the [System.Web.Http.Authorize] attribute to authorize my web API. But for some reason, the API redirects the login page in the same way as my MVC application due to the above configuration.
what I want to do is keep the redirect function for web MVC, but returns 401 for web API. How can i achieve this? Should I create a custom authorization attribute for the web API?
- EDIT -
I found the answer from this post SuppressDefaultHostAuthentication in WebApi.Owin also suppresses authentication outside of webapi
So, I just add a few lines to my Startup.cs . I had all my controllers configured with the api prefix.
HttpConfiguration config = new HttpConfiguration(); //..some OWIN configuration app.Map("/api", inner => { inner.UseWebApi(config); });
make sure you put app.Map() after the web api configuration lines. Otherwise, the MVC application will fail.
source share