Saturday, November 7, 2009

WCF REST HttpStatusCode.Unauthorized status code does not work

Alternate title: WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized does not work.
Alternate title: HttpStatusCode.Unauthorized turned into HttpStatusCode.NotFound

The problem:
I spent at least three hours tracking this stupid thing down. The problem that I ran into was Forms Authentication. What's happening is that I am returning HttpStatusCode.Unauthorized (401), but forms authentication is routing the error to the login page. If you don't have a Login.aspx, you will get a resource not found error (HttpStatusCode.NotFound - 404).

If you can change your authentication mode to Windows and the problem goes away, you have this problem.
If you use the browser to hit your REST web service that requires authentication (it returns a 401 status code) and it routes you to your aspx login screen, you have this problem.

Possible solutions:
  • Check out this MSDN article: Supporting HTTP Authentication and Forms Authentication in a Single ASP.NET Web Site . If for some reason this link dies, search for Mixed Authentication Disposition ASP.NET Module (MADAM), which the name of the HttpModule that the MSDN article talks about that allows you to use both HTTP authentication (in this case basic/digest) and Forms authentication in the same web site.
  • I did run across a couple of post were people wanted to use both Windows and Forms authentication together. In those post, it was suggested that the people create a virtual directory in IIS so that you could have two different web.config that specify different authentication methods. I don't know if this will work for this problem, but it is a possible alternative.