Showing posts with label cookies. Show all posts
Showing posts with label cookies. Show all posts

Saturday, March 14, 2009

Secure WCF Services with Authentication Service

We can use WCF Authentication Service to authenticate users with ASP.NET membership provider. However, other WCF services are not protected by the authentication service out-of-the-box. That is, WCF services is not using ASP.NET forms authentication.

Fortunately, it is not hard to enable it. The magic point is set the HttpContext.Current.User in Global.asax
public class Global : System.Web.HttpApplication
{
// other methods snipped...
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie ticketCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (null == ticketCookie)
{
return;
}

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(ticketCookie.Value);
if (null != ticket)
{
HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), null);
}
}
}
In the service you want to protect, set the requirement mode to allowed or required.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class PrimeService : IPrimeService
Then, throw in the following checking at the beginning of the method.
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
throw new FaultException<SecurityAccessDeniedException>(new SecurityAccessDeniedException());
}
That would be good enough for Silverlight client. For .Net WCF client, you need to handle the HTTP cookies by yourself (Authentication Service is using the authentication ticket in cookies). Detail discussion can be found in the article in Shane's Shelf.