asp.net mvc 3 - set global user data

Santiago picture Santiago · May 8, 2011 · Viewed 13.1k times · Source

How can I set global user data that retain some information like name, lastname, etc through pages? If I use session variable it expires before auth cookie

thanks!

Answer

LukeP picture LukeP · May 8, 2011

You can store data for the time of auth session by utilising userdata field in auth cookie.

Code below is the LogOn action from AccountController in default MVC project:

 [HttpPost]
 public ActionResult LogOn(LogOnModel model, string returnUrl)
 {
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

You can replace:

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

with:

string fullName = "User full name";

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, model.Email, DateTime.Now,
                DateTime.Now.AddDays(2), model.RememberMe, fullName);

string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.AddDays(2) });

If you want to store more data than you can pack in a normal string you will have to look into some sort of data serializer.

Then, you will have to implement something to parse serialized data when auth cookie is used.

Data is available through:

((FormsIdentity)User.Identity).Ticket.UserData;

Hope that helps

Edit: Also change DateTime.Now.AddDays(2) to whatever you want your auth session to remain valid.