protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); // why do authCookie has the data we need? where did it get them??? if (authTicket != null) //here we could also checkif it's expired { //The following part is different with authentication2 //Need to figure out why SchoolPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <SchoolPrincipalSerializeModel>(authTicket.UserData); // turned from JSON back to original form var newUser = new SchoolPrincipal(authTicket.Name) //name the new principal with the username { // generally, as long as user has Iprincipal, things would be find UserId = serializeModel.UserId, FirstName = serializeModel.FirstName, LastName = serializeModel.LastName, Roles = serializeModel.Roles }; //if (newUser != null) //{ HttpContext.Current.User = newUser; //} } } }
public ActionResult Login(LoginViewModel login) { try { // TODO: Add insert logic here if (ModelState.IsValid) { var user = db.User.FirstOrDefault(u => u.Username == login.Username && u.Password == login.Password); //this part is what the GetUserDetails() did in Authentication2 //But why don't we make a user object like in Authentication2? Such as: //User user = new User() { Email = model.Email, Password = model.Password }; //从model中取email和密码,建立user if (user != null) //if user is valid: { var userRoles = user.Roles.Select(r => r.RoleName).ToArray(); //take all the role name of this one user var serializeModel = new SchoolPrincipalSerializeModel { UserId = user.UserId, FirstName = user.FirstMidName, LastName = user.LastName, Roles = userRoles }; //why do we serialize it? is it nessesary? in authentication2, we didn't, why? var userData = JsonConvert.SerializeObject(serializeModel); // why not use FormsAuthentication.SetAuthCookie(model.Email, false); like in authentication2? //THen the following lines are the same with authentication2 var authTicket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData); var encTicket = FormsAuthentication.Encrypt(authTicket); var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); //why it's the same with HttpContext.Response.Cookies.Add(authCookie)? return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "Incorrect username and/or password"); } return(View()); } catch { return(View()); } }