private static void SetUserFromAuthTicket(FormsAuthenticationTicket authTicket) { BasicPrincipalSerializationModel serializeModel = new JavaScriptSerializer().Deserialize<BasicPrincipalSerializationModel>(authTicket.UserData); BasicPrincipal user = new BasicPrincipal(authTicket.Name) { Id = serializeModel.Id, ClientId = serializeModel.ClientId, ClientName = serializeModel.ClientName, Username = serializeModel.Username }; HttpContext.Current.User = user; }
public ActionResult Login(AuthenticationViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } User user = _adminRepo.GetUserByUsername(model.Username); if (user != null) { if (user.AuthentiateUser(user.Username, model.Password)) { FormsAuthentication.SetAuthCookie(user.Username, false); Client userClient = _adminRepo.GetClientById(user.ClientId); // get the auth ticket and set the cookie BasicPrincipal principal = new BasicPrincipal(user, userClient.Name); BasicPrincipalSerializationModel serializationModel = principal.Serialize(); string userData = new JavaScriptSerializer().Serialize(serializationModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(300), false, userData, FormsAuthentication.FormsCookiePath); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)) { Domain = FormsAuthentication.CookieDomain, HttpOnly = true }; System.Web.HttpContext.Current.Response.Cookies.Set(cookie); if (user.Username == "admin") { return RedirectToAction("Index", "Home", new {area = "Admin"}); } return RedirectToLocal(returnUrl); } } ModelState.AddModelError("", "Invalid login attempt."); return View(model); }