Basic Authentication with WCF Web API hosted in IIS / Getting a 404 - Disable Forms Authentication Redirection

Written on August 23, 2011

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:

Authentication Settings

No Forms Authentication activated -- what the heck?

Ok, lets disable Authentication in web.config explicitely:

      <authentication mode="None" />

Yet another test:

another 302 404

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:

        <modules runAllManagedModulesForAllRequests="true">
            <remove name="FormsAuthentication" />

When firing our request once again, we get this:


I presume you've never been happier to get a 401 Winking smile

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 Winking smile

DotNetKicks-DE Image