When you’re hosting WCF Web API inside an ASP.NET MVC 3 Website and doing Basic Authentication you may stuck with the following problem:
According to REST principles your Basic Authentication implementation will return a 401 (Unauthorized) status code.
But your client gets a 404 (Not Found).
First, lets do some investigation and then get rid of it.
Assuming we’re trying to GET http://wcfwebapibasicauth/contacts and send no Authorization header with it, we’ll get the following output in Fiddler:
As you can see, our request does not send the 401 but does a 302 instead (which is a redirect) to the default ASP.NET MVC Login View of the Account-Controller.
Of course the first thing you may check are the Authentication settings in IIS:
No Forms Authentication activated – what the heck?
Ok, lets disable Authentication in web.config explicitely:
<authentication mode="None" />
Yet another test:
Still 404… so, what happens?
Even if it is disabled, ASP.NET Forms Authentication module intercepts our 401 from the Basic Authentication Handler and does the redirect.
If you’re using IIS and the ASP.NET MVC Web Site just for the sake of hosting your Web API you’re almost done – just remove the ASP.NET Forms Authentication in your web.config:
<remove name="FormsAuthentication" />
When firing our request once again, we get this:
I presume you’ve never been happier to get a 401
If you’re co-hosting your Web API with an MVC 3 page and you’ll need Forms Authentatication, this trick will not work.
You may then end up with a solution Amila show's here: Prevent forms auth from redirecting to login page in RESTFul WCF.
You can optimize it by adding determination whether your 302 came from the MVC page or the Web API by evaluation the Request.Url which should contain the originally request URI.
For now we’re done – happy authenticating