Zulfiqar's weblog

Architecture, security & random .Net

Flowing Forms Authentication Cookie to WCF

Posted by zamd on March 5, 2009

Client Application Services enables the use of Authentication and other ASP.net services outside of ASP.net applications. Here I will show how you can configure WCF to flow Forms authentication cookie (acquired after successful authentication) to a WCF service (running in ASP.net compatibility mode).

static void Main(string[] args)


    //Authenticate using membership API.

    var valid = Membership.ValidateUser("Zul", "G!");


    var identity = Thread.CurrentPrincipal.Identity as ClientFormsIdentity;


    ServiceReference1.Service1Client sc = new FormsAuClient.ServiceReference1.Service1Client();


    using (var ocs = new OperationContextScope(sc.InnerChannel as IContextChannel))


        var ch = identity.AuthenticationCookies.GetCookieHeader(sc.Endpoint.ListenUri);


        HttpRequestMessageProperty rmp = new HttpRequestMessageProperty();

        rmp.Headers[HttpRequestHeader.Cookie] = ch;


        // enable cookie flow for WCF Http Transport Channel.

        var col = sc.Endpoint.Binding.CreateBindingElements();

        var transport = col.Find<HttpTransportBindingElement>();

        transport.AllowCookies = true;


        sc.Endpoint.Binding = new CustomBinding(col);


        // Add Forms Authentication Cookie to outgoing message.

        OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, rmp);




On the server side, WCF service is running under ASP.net compatibality mode along with Forms Authentication configured in web.config

Note, for this configuration to work – both apps (sharing the cookie) MUST use the same/explicit machine key.

PS: There is a general misunderstanding that WCF doesn’t allow control over HTTP headers/body which lead few people think that this is not possible in WCF.



4 Responses to “Flowing Forms Authentication Cookie to WCF”

  1. zamd said

    That is awesome. Thank you, I have been looking for a way to do this…

  2. nathan manny said

    Great article…Although there is

    Calling var identity = Thread.CurrentPrincipal.Identity as ClientFormsIdentity;

    returns a null to identity even though I can see a valid Thread.CurrentPrincipal.Identity. Any suggestions…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: