protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); CoffeeShopPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <CoffeeShopPrincipalSerializeModel>(authTicket.UserData); CoffeeShopPrincipal newUser = new CoffeeShopPrincipal(authTicket.Name); newUser.UserId = serializeModel.UserId; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; newUser.Roles = serializeModel.Roles; HttpContext.Current.User = newUser; } }
public ActionResult Login(UserLoginViewModel model) { // Get user info var user = Context.Users .Where(u => u.Username == model.Username) .FirstOrDefault(); // Verify password if (user != null && SaltedHash.Verify(user.Salt, user.Password, model.Password)) { var roles = user.Roles.Select(r => r.RoleName).ToArray(); CoffeeShopPrincipalSerializeModel serializeModel = new CoffeeShopPrincipalSerializeModel(); serializeModel.UserId = user.UserId; serializeModel.FirstName = user.FirstName; serializeModel.LastName = user.LastName; serializeModel.Roles = roles; string userData = JsonConvert.SerializeObject(serializeModel); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, user.Username, DateTime.Now, DateTime.Now.AddHours(24), model.RememberMe, userData); string encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); return(RedirectToAction("Index", "Finance")); } else { ModelState.AddModelError("", "Sai tên đăng nhập hoặc mật khẩu!"); return(View(model)); } }