Andy Clark
Andy Clark

Reputation: 3523

MVC 3 Cookies not working

I am using forms authentication for an MVC website and I am having a problem adding Cookies, I am using an Encrypted Forms Authentication Ticket and adding it to the Cookies but when inspecting my cookies it is there (by name "AuthCookie") but the value is always null and the Expires date is always set to "01/01/0001 00:00"... here is my Login controller code:

[HttpPost]
public ActionResult Index(Login login, string returnUrl)
{
    if (ModelState.IsValid)
        try
        {
            User user = UserManager.Login(login.Username, login.Password);
            string serialUser = Serialize.SerializeToString(user);
            string ticket = FormsAuthentication.Encrypt(
                new FormsAuthenticationTicket(1, login.Username, DateTime.Now, DateTime.Now.AddMinutes(20.0), login.RemeberMe, serialUser));

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket) { Expires = DateTime.Now.AddMinutes(20) };
            Response.Cookies.Add(cookie);


            if (String.IsNullOrEmpty(returnUrl))
                return RedirectToAction("Index", "Home");
            else
                return Redirect(returnUrl);
        }
        catch (LoginFailedException)
        {
            ModelState.AddModelError("", "Login failed: Invalid Username or Password.");
            return View(login);
        }
    else
        return View(login);

}

At first I assumed the encrypted string was not working due to the length but I have tested this by creating a simple test cooke and I am getting the same result.

Can anyone help

Upvotes: 2

Views: 1803

Answers (1)

Jon Galloway
Jon Galloway

Reputation: 53115

When you call Redirect() or RedirectToAction(), you're terminating the response so the cookies aren't sent to the client. Some solutions:

  1. Use TempData to persist the information across the direct, writing the Cookie in the action you redirect to.
  2. Take a look at the way Forms Authentication cookie information is written in the NerdDinner code on CodePlex.
  3. As mentioned in the comments, you can persist role information in Session. The recommendation to store the role information in Session and retrieve from Roles if not found would work, but I'd start by using the membership system as-is and performance tuning later if you see that it's a problem, rather than assuming it will be.

Upvotes: 3

Related Questions