public static ClaimsIdentity CreateIdentity(UserModel user, string authenticationType) { var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); identity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.AccountId.ToString())); identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity")); identity.AddClaim(new Claim("Id", user.AccountId.ToString())); return identity; }
public ActionResult Login(LoginViewModel model, string returnUrl) { var userModel = new UserModel(); if (!ModelState.IsValid) return View(model); var user = _accountService.GetAccounts().FirstOrDefault(n => n.IsDeleted == false && (n.Employee.Mail == model.UserName || n.Employee.PhoneNumber == model.UserName) && n.Password == model.Password); if (user != null) { userModel.Name = user.Employee.Name; userModel.EmployeeId = user.Employee.Id; userModel.AccountId = user.Id; var identity = UserService.CreateIdentity(userModel, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, identity); return RedirectToLocal(returnUrl); } ModelState.AddModelError("", "Invalid username or password."); // 如果我们进行到这一步时某个地方出错,则重新显示表单 return View(model); }