14

Okay, I've had little luck finding any documentation or tutorials for my specific scenario.

I have an ASP.Net MVC web application that will be using WCF services for everything including authentication and roles (via membership providers on the WCF backend).

I've had no problem setting up the authentication services but it does not set a cookie in the web app. The docs for the Login method of the service indicate that wiring up the CreatingCookie Event is possible, but it does not have any affect on the client (I tried on the service side as well, again no affect). So I figured out how to capture the cookie. I have tried to manually set the auth cookie on the client, but so far it is not working; decrypting fails due to padding, and setting the cookie value from the one given by the server is not readable by the client.

Does anybody know how you are supposed to use the cookie that is generated by the WCF Authentication Service? Do I just assume the session is all managed on the WCF server and just check IsLoggedIn() on the service at every page load?

Thanks in advance.

1
  • reading through more documentation on MSDN, I guess my scenario was never intended by MS; if you are going to use membership on a website, why would you ever authenticate to a service instead of hitting the db directly, so it looks like a website has to be handled the same as any other client, which means manually grabbing the cookies from the header and making use of them yourself (creating a principal, auth ticket, etc and assigning them to the proper parts of the website so it can be used). will investigate more and hopefully have an answer to post ...
    – tap
    Commented Apr 7, 2010 at 4:02

2 Answers 2

11

I have recently been trying to implement the same functionality you have described. I have managed to get it working with the following code:

    private readonly AuthenticationServiceClient service = new AuthenticationServiceClient();

    public void SignIn(string userName, string password, bool createPersistentCookie)
    {
        using (new OperationContextScope(service.InnerChannel))
        {
            // login
            service.Login(userName, password, String.Empty, createPersistentCookie);

            // Get the response header
            var responseMessageProperty = (HttpResponseMessageProperty)
                OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];

            string encryptedCookie = responseMessageProperty.Headers.Get("Set-Cookie");

            // parse header to cookie object
            var cookieJar = new CookieContainer();
            cookieJar.SetCookies(new Uri("http://localhost:1062/"), encryptedCookie);
            Cookie cookie = cookieJar.GetCookies(new Uri("http://localhost:1062/"))[0];

            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            if (null != ticket)
            {
                //string[] roles = RoleManager.GetRolesFromString(ticket.UserData); 
                HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), null);
                FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, createPersistentCookie);
            }
        }
    }

It does exactly what you have described the comment to your question.

EDIT

I am posting here the Server-Side portion of this code for reference.

public class HttpResponseMessageInspector : BehaviorExtensionElement, IDispatchMessageInspector, IServiceBehavior
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {

        HttpRequestMessageProperty httpRequest = request.Properties[HttpRequestMessageProperty.Name]
        as HttpRequestMessageProperty;

        if (httpRequest != null)
        {
            string cookie = httpRequest.Headers[HttpRequestHeader.Cookie];

            if (!string.IsNullOrEmpty(cookie))
            {
                FormsAuthentication.Decrypt(cookie);
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(cookie);
                string[] roles = PrincipalHelper.GetUserRoles(authTicket);
                var principal = new BreakpointPrincipal(new BreakpointIdentity(authTicket), roles);

                HttpContext.Current.User = principal;                  
            }
            // can deny request here
        }

        return null;
    }
}
5
  • wow, I did miss some tricks.. Let me see how this works and I'll get back to you. No matter what I really appreciate your effort and taking an interest :)
    – tap
    Commented Apr 13, 2010 at 22:27
  • this looks good on the surface, but I am seeing the same issue I ran into: System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. My assumption on this error is that since it is 2 different contexts (client application and service application), the decrypt/encrypt is not compatible? How did you set this up to work? Again thanks for taking an interest and the effort :)
    – tap
    Commented Apr 14, 2010 at 0:18
  • Is the Asp.net MVC and WCF Host application running on the same machine? If not you will have to set both Web.config to use the same machine key. See [msdn.microsoft.com/en-us/library/ms998288.aspx] In my setup, both MVC and WCF Service Host are running within Visual Studio WebServer on my local machine. So the machine key would be the same. EDIT: Also you can try adding this code to you WCF Host Global.cs file to explicitly send a cookie just to rule out more one thing: msdn.microsoft.com/en-us/library/bb398778%28v=VS.100%29.aspx
    – Karl
    Commented Apr 14, 2010 at 0:42
  • I do have them running on the same box right now, but I'm running off IIS7 and not cassini, so machine key should already be the same. will look into the links. thanks
    – tap
    Commented Apr 14, 2010 at 16:54
  • This worked for me: string encryptedTicket = cookie.Replace(String.Format("{0}=", FormsAuthentication.FormsCookieName), String.Empty); Commented Sep 19, 2012 at 15:37
2

This works for me... First setup the authentication behavior of the host (here shown through code, but can also be done in config):

ServiceAuthorizationBehavior author = Description.Behaviors.Find<ServiceAuthorizationBehavior>();
author.ServiceAuthorizationManager = new FormCookieServiceAuthorizationManager();
author.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
author.ExternalAuthorizationPolicies = new List<IAuthorizationPolicy> { new CustomAuthorizationPolicy() }.AsReadOnly();

And then the helper classes

  internal class FormCookieServiceAuthorizationManager : ServiceAuthorizationManager
  {
     public override bool CheckAccess(OperationContext operationContext)
     {
        ParseFormsCookie(operationContext.RequestContext.RequestMessage);
        return base.CheckAccess(operationContext);
     }
     private static void ParseFormsCookie(Message message)
     {
        HttpRequestMessageProperty httpRequest = message.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
        if (httpRequest == null) return;

        string cookie = httpRequest.Headers[HttpRequestHeader.Cookie];
        if (string.IsNullOrEmpty(cookie)) return;

        string regexp = Regex.Escape(FormsAuthentication.FormsCookieName) + "=(?<val>[^;]+)";
        var myMatch = Regex.Match(cookie, regexp);
        if (!myMatch.Success) return;

        string cookieVal = myMatch.Groups["val"].ToString();
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(cookieVal);
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), new string[0]);
     }
  }
  internal class CustomAuthorizationPolicy : IAuthorizationPolicy
  {
     static readonly string _id = Guid.NewGuid().ToString();
     public string Id
     {
        get { return _id; }
     }

     public bool Evaluate(EvaluationContext evaluationContext, ref object state)
     {
        evaluationContext.Properties["Principal"] = Thread.CurrentPrincipal;
        evaluationContext.Properties["Identities"] = new List<IIdentity> { Thread.CurrentPrincipal.Identity };
        return true;
     }

     public ClaimSet Issuer
     {
        get { return ClaimSet.System; }
     }
  }

And for when AspNetCompatibility is set, then FormCookieServiceAuthorizationManager is slightly simpler:

 internal class FormCookieServiceAuthorizationManager : ServiceAuthorizationManager
 {
    public override bool CheckAccess(OperationContext operationContext)
    {
       Thread.CurrentPrincipal = HttpContext.Current.User;
       return base.CheckAccess(operationContext);
    }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.