public ActionResult Login(TaiKhoanVm taiKhoanVm) { if (ModelState.IsValid) { if (ValidateRequest) { if (taiKhoanVm.TenTaiKhoan == taiKhoanVm.MatKhau) { var id = new CustomeIdentity(taiKhoanVm.TenTaiKhoan); var roles = new string[] { "nhanvien" }; var pricipal = new CustomePricipal(id, roles); Thread.CurrentPrincipal = pricipal; HttpContext.User = pricipal; var data = new UserData { UserId = 1, Email = "*****@*****.**", Address = "4.34 Chung Cu Nhieu Loc", Roles = roles }; var userData = JsonConvert.SerializeObject(data); var ticket = new FormsAuthenticationTicket(1, taiKhoanVm.TenTaiKhoan, DateTime.Now, DateTime.Now.AddMinutes(30), true, userData); var strTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket); cookie.HttpOnly = true; Response.Cookies.Add(cookie); return(RedirectToAction("Index", "Home")); } } } return(RedirectToAction("Index", "TaiKhoan")); }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User.Identity.IsAuthenticated) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); UserData userData = JsonConvert.DeserializeObject <UserData>(ticket.UserData); var id = new CustomeIdentity(ticket.Name) { Email = userData.Email, Address = userData.Address, Id = userData.UserId }; var roles = Roles.GetRolesForUser(ticket.Name); var principal = new CustomePricipal(id, roles); //var principal = new CustomePricipal(id,userData.Roles); HttpContext.Current.User = principal; } } }