Question

I've been fighting with this for a while. In VS 2012 I created a new MVC4 application using the "Internet Application" project template (for simplicity, I'm also seeing the problem in my regular app using an ExtendedMembershipProvider).

On Login I want to put some UserData in the Forms Authentication cookie, so I use the following code:

public ActionResult Login(LoginModel model, string returnUrl)
{
    Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
    if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
    {
        HttpCookie authCookie = FormsAuthentication.GetAuthCookie(model.UserName, true);
        string userData = "This is some test data.";
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(authTicket.Version, authTicket.Name, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, userData);
        string newAuthTicketEncrypted = FormsAuthentication.Encrypt(newAuthTicket);
        authCookie.Value = newAuthTicketEncrypted;

        Request.Cookies.Set(authCookie);
        // Response.Write("Encrypted cookie value: " + authCookie.Value);  // value here differs than what browser sees
        // Response.Write("UserData: " + FormsAuthentication.Decrypt(authCookie.Value).UserData + "<br/>"); // userdata is present here.
        // return, shortened for brevity

    }

}

Pretty basic. However it is not present in the cookie when I decrypt it. The problem seems to be that something is creating a new forms authentication cookie somewhere else down in the pipeline. I can prove this by printing out the value of the encrypted cookie, and comparing it to the value that appears in my browser after the login request. They are different! Something is recreating the cookie and encrypting it, without UserData present. The name value is present in the cookie - any idea where or what would be doing this? Did MS break UserData in forms authentication with the new WebMatrix methods?

Was it helpful?

Solution

You're setting the cookie on the request you need to set the cookie on the Response object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top