You can use the FormsAuthentication cookie to store user information and not access the database all the time. This cookie is encrypted and all the information you store is as secure as the user's session. The only problem with cookies is that they have a maximum size of 4K, so if your user information is massive, then you may have a problem. When I use the cookie method, I save my user data as JSON and then deserialize the JSON on each page request. Here is my logic controller logic (I use SimpleMembership, but the approach is the same:
public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, model.RememberMe)) { var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { var user = _userLogic.GetItem(model.UserName); if (user != null && user.IsActive) { var newAuthTicket = new FormsAuthenticationTicket(authTicket.Version, authTicket.Name, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, JsonConvert.SerializeObject(user)); var newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(newAuthTicket)) { Expires = authCookie.Expires }; Response.Cookies.Add(newCookie); return RedirectToLocal(returnUrl); } WebSecurity.Logout(); ModelState.AddModelError("UserName", "This account has been deactivated."); return View(model); } } }
Note the creation of newAuthTicket and how the user instance is passed to it as JSON. After that, all I have to do is desirialize this user object in my OnAuthorization method base controller:
protected override void OnAuthorization(AuthorizationContext filterContext) { var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { var principal = new CustomPrincipal(HttpContext.User.Identity) { CurrentUserInfo = JsonConvert.DeserializeObject<User>(authTicket.UserData) }; HttpContext.User = principal; AppUser = principal.CurrentUserInfo; ViewBag.AppUser = AppUser; } } base.OnAuthorization(filterContext); }
Marko source share