Flowing Forms Authentication Cookie to WCF
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);
sc.GetData(32);
}
}
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.