public async Task <IActionResult> Login(LoginVM User) { var defaultRole = _roleManager.Roles.FirstOrDefault(x => x.ApplicationRoleType == ApplicationRoleTypeEnum.适用于普通注册用户); if (defaultRole == null) { await ApplicationDataSeed.ForRolesAndUsers(_roleManager, _userManager); } var user = await _userManager.FindByNameAsync(User.UserName); if (user != null) { // 登录系统 var result = await _signInManager.PasswordSignInAsync(user, User.Password, false, lockoutOnFailure : false); if (result.Succeeded) { var claims = new List <Claim>(); //创建声明,并加入声明组。声明的类型是Name, 值是小明,证书发布者是contoso claims.Add(new Claim(ClaimTypes.Name, user.UserName)); //创建用户身份SuperSecureLogin var userIdentity = new ClaimsIdentity("SuperSecureLogin"); //将声明组加入用户身份userIdentity userIdentity.AddClaims(claims); //创建身份当事者 var userPrincipal = new ClaimsPrincipal(userIdentity); //创建身份认证Cookie await HttpContext.SignInAsync( //默认Cookie认证 CookieAuthenticationDefaults.AuthenticationScheme, //身份证当事者 userPrincipal, //设置认证属性 new AuthenticationProperties { //cookie 到期时间 ExpiresUtc = DateTime.UtcNow.AddMinutes(20), //永久 cookie IsPersistent = false, //允许刷新认证Session AllowRefresh = false }); if (await _userManager.IsInRoleAsync(user, "普通注册用户") && User.UserRole == "普通注册用户") { return(RedirectToAction("Index")); } } else { ModelState.AddModelError("Password", "你输入的用户密码错误,请核实后重新输入。"); return(View(User)); } } return(View()); }
public AccountController( UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager, SignInManager <ApplicationUser> signInManager, SqlServerDbContext context) { _signInManager = signInManager; _userManager = userManager; _roleManager = roleManager; _context = context; ApplicationDataSeed.ForRolesAndUsers(_roleManager, _userManager); }