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);
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.
Email
Twitter
LinkedIn
zamd said
That is awesome. Thank you, I have been looking for a way to do this…
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…
Sridhar said
Same this is happening to me.. did you resolve this?
zamd said
check the Identity type, is it WindowsIdentity or what? You might be missing the FormsAuthenticationModule in your configuration…