Exemplo n.º 1
0
        /// <summary>
        /// 验证用户
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private async Task <List <Claim> > ValidateUserAsync(string loginName, string password)
        {
            return(await Task.Run(() =>
            {
                List <Claim> claims = null;
                bool isValid = false;
                string errMsg = null;
                // 以及角色相关信息,我这里还是使用内存中已经存在的用户和密码
                var testUser = OAuthConfig.GetTestUsers().Find(t => t.Username == loginName && t.Password == password);
                if (testUser != null)
                {
                    claims = new List <Claim>()
                    {
                        new Claim(UserClaimEnum.UserId.ToString(), $"{testUser.SubjectId}"),
                        new Claim(UserClaimEnum.UserName.ToString(), testUser.Username)
                    };
                    isValid = true;
                }
                else
                {
                    //E登账号
                    var edUser = _edApiService.GetEdUser(loginName, password, out string msg);
                    if (edUser != null)
                    {
                        claims = new List <Claim>()
                        {
                            new Claim(UserClaimEnum.UserId.ToString(), $"{edUser.ID}"),
                            new Claim(UserClaimEnum.UserName.ToString(), edUser.EmployeeName)
                        };
                        isValid = true;
                    }
                    errMsg = msg;
                }

                if (!isValid)
                {
                    throw new Exception(errMsg ?? "登录失败,用户名和密码不正确");
                }

                //实际生产环境需要通过读取数据库的信息并且来声明
                return claims;
            }));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            if (ModelState.IsValid)
            {
                AuthenticationProperties props        = null;
                IdentityServerUser       isuser       = null;
                UserLoginSuccessEvent    successEvent = null;
                bool   isValid = false;
                string errMsg  = null;

                // 测试用户
                var testUser = OAuthConfig.GetTestUsers().Find(t => t.Username == model.Username && t.Password == model.Password);
                if (testUser != null)
                {
                    successEvent = new UserLoginSuccessEvent(testUser.Username, testUser.SubjectId, testUser.Username, clientId: context?.Client.ClientId);
                    // issue authentication cookie with subject ID and username
                    isuser = new IdentityServerUser(testUser.SubjectId)
                    {
                        DisplayName      = testUser.Username,
                        AdditionalClaims =
                        {
                            new Claim(UserClaimEnum.UserId.ToString(),   testUser.SubjectId),
                            new Claim(UserClaimEnum.UserName.ToString(), testUser.Username)
                        }
                    };
                    isValid = true;
                }
                else
                {
                    //E登账号
                    var edUser = _edApiService.GetEdUser(model.Username, model.Password, out string msg);
                    errMsg = msg;
                    if (edUser != null)
                    {
                        successEvent = new UserLoginSuccessEvent(edUser.LoginName, edUser.ID.ToString(), edUser.EmployeeName, clientId: context?.Client.ClientId);
                        // issue authentication cookie with subject ID and username
                        isuser = new IdentityServerUser(edUser.ID.ToString())
                        {
                            DisplayName      = edUser.EmployeeName,
                            AdditionalClaims =
                            {
                                new Claim(UserClaimEnum.UserId.ToString(),   edUser.ID.ToString()),
                                new Claim(UserClaimEnum.UserName.ToString(), edUser.EmployeeName.ToString())
                            }
                        };
                        isValid = true;
                    }
                }

                if (isValid)
                {
                    //身份认证通过
                    await _events.RaiseAsync(successEvent);

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;
                    await HttpContext.SignInAsync(isuser, props);

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            // The client is native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }
                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }
                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("无效的返回URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "无效的证书", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, errMsg ?? AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }