Exemplo n.º 1
0
        public async Task <IActionResult> Login(LoginModel model, string returnUrl = null)
        {
            //验证码应该做加密处理,不然形同虚设
            HttpContext.Request.Cookies.TryGetValue("LoginVerifyCode", out var verifyCode);
            verifyCode = HashEncrypt.DESDecrypt(verifyCode, "hpmcgctr");
            if (!model.VerifyCode.Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase))
            {
                return(Json(new
                {
                    Success = false,
                    Message = "验证码错误!"
                }));
            }
            if (model.UserName != AppSettings.DefaultUserName || model.Password != AppSettings.DefaultPassword)
            {
                return(Json(new
                {
                    Success = false,
                    Message = "用户名或密码错误!"
                }));
            }

            // create claims
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, model.UserName),
            };

            // create identity
            ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationConfig.AuthenticationKey);

            // create principal
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            // sign-in
            await HttpContext.SignInAsync(
                scheme : AuthenticationConfig.AuthenticationKey,
                principal : principal,
                properties : new AuthenticationProperties
            {
                IsPersistent = true,         // for 'remember me' feature
                ExpiresUtc   = DateTime.UtcNow.AddHours(12),
                AllowRefresh = false
            });

            returnUrl = returnUrl ?? ViewData["ReturnUrl"] as string;
            if (!string.IsNullOrWhiteSpace(returnUrl))
            {
                return(Json(new
                {
                    Success = true,
                    Message = "登录成功!",
                    ReturnUrl = returnUrl
                }));
            }
            return(Json(new
            {
                Success = true,
                Message = "登录成功!",
                ReturnUrl = "/home/index"
            }));
        }