コード例 #1
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var result = await _userServer.CheckEmailAndPasswordAsync(model.Email, model.Password);

                if (result == Models.SignInResult.Success)
                {
                    var identity  = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal = new ClaimsPrincipal(identity);
                    identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
                    identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    //验证是否授权成功
                    if (principal.Identity.IsAuthenticated)
                    {
                        return(RedirectToAction("Home/Index"));
                    }
                    _logger.LogInformation("User logged in.");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "用户名或密码错误!");
                    _logger.LogError("用户{userName}登录时发生错误!", model.Email);
                    return(View());
                }
            }
            // If we got this far, something failed, redisplay form
            return(RedirectToLocal(returnUrl));
        }