public static string GetAuthTicketAsString(User user, bool isPersistent) { if (user == null) throw new ArgumentNullException("user"); CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel(); serializeModel.UserId = user.Id; serializeModel.Email = user.Email; serializeModel.Role = user.Role.Name; string userData = JsonConvert.SerializeObject(serializeModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(15), isPersistent, userData); string encTicket = FormsAuthentication.Encrypt(authTicket); return encTicket; }
public ActionResult Register(RegisterViewModel model) { if (ModelState.IsValid) { var anyUser = context.Users.Any(user => user.Email == model.Email); if (anyUser) ModelState.AddModelError("Email", "This email is already registered"); else { User user = new User() { Email = model.Email, Password = model.Password, RoleId = 2, //user CreationDate = DateTime.Now }; context.Users.Add(user); context.SaveChanges(); user = context.Users .Where(u => u.Email == model.Email) .Include(u => u.Role) .FirstOrDefault(); string encTicket = AuthenticationHelper.GetAuthTicketAsString(user, false); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); return RedirectToAction("Index", "Home"); } } return View(model); }