Prevent forms auth from redirecting to login page in RESTFul WCF

In this post I am going to explain how to prevent a WCF service from sending HTTP 302 redirects to the login.aspx when used with the forms authentication.

RESTFul web services are becoming more popular than the traditional SOAP based .asmx web services and if you still don’t know about then check out this Wikipedia article

Microsoft has a great starter kit for building REST WCF services here

So back to the article now.

If you are using forms authentication to authenticate a WCF REST service, when the user authentication fails, the service sends a http redirect to the login page. But since this is a web service what we want is a login exception not a web page.

The reason for this is that the forms authentication is primarily designed with the web sites in mind and the redirecting to the login page in the event of a login failure is the expected behavior for a site.

But thanks to the extensibility of the WCF we can work around this limitation.

What we need is to catch the http 302(redirect) sent by the forms auth module before sending it to the user, and change it to a http 401 (unauthorized) and send.

So here’s how to do it;

Step 1. Create an HttpModule

First we need to implement a http module. (If you don’t know what that is, think of it as an evil being who catches the responses before they are sent to the user) 🙂

So here’s the code for that. I named it as AuthRedirectHandler but you can use any name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MyRest
    class AuthRedirectHandler : IHttpModule

        #region IHttpModule Members

        public void Dispose()


        public void Init(HttpApplication context)
            context.EndRequest+= new EventHandler(context_EndRequest);

        void context_EndRequest(object sender, EventArgs e)
            HttpApplication app = (HttpApplication)sender;
            if (app.Response.StatusCode == 302)
                app.Response.StatusCode = 401;


In the above class we catch the response in the context_EndRequest method and if it is a http redirect, clears all the content, headers and set the status code to 401 (unauthorized). Note that the changing the status code alone won’t be enough but this code will clear the cookies as well 🙁 .

Step 2. Modify the web.config to use the HttpModule

Ok now we have the http module and now we want to tell our service to use it to handle the http requests.

And here’s how to do that.

Go to the web.config in your WCF service and add the following to the <system.web> section

      <add name="AuthRedirectHandler" type="MyRest.AuthRedirectHandler, MyRest" />

Now run your service and it won’t send you redirects to login page anymore.

Happy coding