Пример #1
0
        public bool SSOLogout(LoginInfoDto loginInfo)
        {
            bool result = false;

            var oAuthValidateDto = GetOAuthValidateDto(loginInfo.AccessToken);

            if (oAuthValidateDto != null)
            {
                SessionModel sessionModel = new SessionModel()
                {
                    SessionID = oAuthValidateDto.Code
                };

                if (sessionManager.IsExist(sessionModel))
                {
                    result = sessionManager.RemoveSession(sessionModel);
                }
                else
                {
                    result = true;
                }
                if (result)
                {
                    OAuthValidateDto dto = new OAuthValidateDto()
                    {
                        Code = oAuthValidateDto.Code
                    };

                    result = oAuthValidateRepository.Delete(dto.ToEntity()) > 0;
                }
            }
            return(result);
        }
Пример #2
0
        private void SaveValidate(string state, string scope, LoginInfoDto loginInfo)
        {
            //分配sessionId
            loginInfo.Code = this.SessionChangeDB.Pop(state);
            if (string.IsNullOrWhiteSpace(loginInfo.Code))
            {
                //TODO:这个地方有时候会有问题,要加入日志
                throw new Exception("Code不能为空");
            }
            System.Threading.Tasks.Parallel.Invoke(() =>
            {
                OAuthValidateDto oAuthValidateDto = new OAuthValidateDto
                {
                    Code          = loginInfo.Code,
                    EmployeeID    = loginInfo.EmployeeID,
                    Password      = loginInfo.Password,
                    ServiceNumber = loginInfo.ServiceNumber,
                    CodeExpire    = 1200,    //默认值
                    CreatedBy     = "admin", //TODO:待修改
                    ModifiedBy    = "admin", //TODO:待修改
                    State         = state,
                    Token         = Serializer.ToJson(Token),
                    Scope         = scope,
                    AccessToken   = Serializer.ToJson(AccessToken)
                };

                OAuthValidateService.Save(oAuthValidateDto);
            }, () =>
            {
                SaveSession(loginInfo.Code);
            });
        }
Пример #3
0
        public async Task <IActionResult> Index(LoginInfoDto loginInfoDto)
        {
            if (!ModelState.IsValid)
            {
                return(View(loginInfoDto));
            }
            SOApiResult <string> resultGetToken = await _userService.GetToken(loginInfoDto);

            if (resultGetToken.IsSucceed && !string.IsNullOrEmpty(resultGetToken.ReturnedData))
            {
                string          token         = resultGetToken.ReturnedData;
                ClaimsPrincipal userPrincipal = this.ValidateToken(token);
                //cookie
                var authProp = new AuthenticationProperties()
                {
                    ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(SystemValue.TIMELIFE_COOKIE_MINUTES),
                    IsPersistent = true,
                };

                //Save cookie to Browser - IMPORTANT
                //The final step validate CookieAuthen
                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    userPrincipal,
                    authProp);

                HttpContext.Session.SetString(SystemValue.TOKEN_NAME, token);

                return(RedirectToAction("Index", "Home"));
            }
            //Log Here
            ModelState.AddModelError("Exception", resultGetToken.Message);
            return(View());
        }
        public virtual LoginInfoDto Login(LoginParamDto vm)
        {
            LoginInfoDto result = null;

            if (vm != null && !string.IsNullOrEmpty(vm.Account) && !string.IsNullOrEmpty(vm.Password))
            {
                var repository = this.GetRepository <IUserRepository>();
                var id         = repository.GetId(vm.Account);
                if (id > 0)
                {
                    var m = repository.Get(id);
                    if (m != null)
                    {
                        if (string.IsNullOrEmpty(m.Password))
                        {
                            if (string.Compare(m.Account, "admin", true) == 0)
                            {
                                m.Password = EncryptUtils.Encrypt("admin");
                                repository.UpdatePassword(m.Id, m.Password);
                            }
                            else if (string.Compare(m.Account, "sync", true) == 0)
                            {
                                m.Password = EncryptUtils.Encrypt("sync");
                                repository.UpdatePassword(m.Id, m.Password);
                            }
                        }
                        string pwd = EncryptUtils.Decrypt(m.Password);
                        if (pwd == vm.Password)
                        {
                            result = new LoginInfoDto()
                            {
                                Id       = m.Id,
                                Account  = m.Account,
                                Name     = m.Name,
                                RoleId   = m.RoleId,
                                RoleName = ""
                            };
                            var roleRepository = this.GetRepository <IRoleRepository>();
                            var role           = roleRepository.Get(m.RoleId);
                            if (role != null)
                            {
                                result.RoleName = role.Name;
                            }
                            var roleAuthRepository = this.GetRepository <IRoleAuthRepository>();
                            result.RoleAuth = roleAuthRepository.GetList(m.RoleId);

                            var user = SessionUtils.UserInfo;
                            user.Id          = result.Id;
                            user.Account     = result.Account;
                            user.Name        = result.Name;
                            user.RoleId      = result.RoleId;
                            result.SessionId = user.SessionId;
                            OptionLogService.Instance.Add(OptionLogType.Login, "登录!");
                        }
                    }
                }
            }

            return(result);
        }
Пример #5
0
        public IActionResult Token([FromBody] LoginViewModel viewModel)
        {
            if (ModelState.IsValid)                       //判断是否合法
            {
                if (string.IsNullOrEmpty(viewModel.User)) //判断账号密码是否正确
                {
                    return(BadRequest());
                }
                WebServiceRequest webServiceRequest = new WebServiceRequest();

                LoginInfoDto userDto = webServiceRequest.SSOLogin(viewModel.User, viewModel.Password);
                var          claim   = new Claim[] {
                    new Claim(ClaimTypes.Name, userDto.User.LoginName),
                    new Claim(ClaimTypes.Role, "admin"),
                    new Claim(ClaimTypesExt.GroupId, userDto.User.GroupID),
                    new Claim(ClaimTypesExt.LoginNo, userDto.User.LoginNo),
                    new Claim(ClaimTypesExt.MenuList, userDto.User.MenuList)
                };

                //对称秘钥
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
                //签名证书(秘钥,加密算法)
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间
                var token = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now, DateTime.Now.AddMinutes(30), creds);

                return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }));
            }

            return(BadRequest());
        }
Пример #6
0
        /// <summary>
        /// Method responsible for send the user credentials to api for validation and check the user role in the system.
        /// </summary>
        ///
        /// <param name="email"> user email to login in the system</param>
        /// <param name="password"> user password to login in the system</param>
        ///
        /// <returns>An object with the user roles in the system</returns>
        /// <exception cref="ApiNotAvailableException"></exception>
        /// <exception cref="NoSuccessfulResponseException"></exception>
        public async Task <Users> Login(string email, string password)
        {
            try
            {
                var loginInfo = new LoginInfoDto {
                    Email = email, Password = password
                };
                string json = JsonConvert.SerializeObject(loginInfo, Formatting.Indented,
                                                          new JsonSerializerSettings {
                    ContractResolver = _contractResolver
                });
                var requestContent          = new StringContent(json, Encoding.UTF8, "application/json");
                var cancellationTokenSource = new CancellationTokenSource(Constants.Timeout);
                var response = await _client.PostAsync(Links.LoginUri, requestContent, cancellationTokenSource.Token);

                response.EnsureSuccessStatusCode();
                var content = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <Users>(content));
            }
            catch (OperationCanceledException operationCanceledException)
            {
                throw new ApiNotAvailableException(AppResources.OperationNotPossibleMessage, operationCanceledException);
            }
            catch (HttpRequestException httpRequestException)
            {
                throw new NoSuccessfulResponseException(AppResources.LoginErrorMessage, httpRequestException);
            }
        }
Пример #7
0
        public RedirectResult Login(LoginInfoDto loginInfo)
        {
            string message = string.Empty;

            //TODO:对客户端构造的url进行解析,验证成功后的returnUrl
            //来查找给对应servernumber是否存在
            NameValueCollection nameValue = HttpContext.Request.QueryString;
            string curLogin = "******";

            ValidateRequestDto validateDto = new ValidateRequestDto()
            {
                AccessToken  = nameValue[QueryKeyMenu.accessToken.ToString()],
                ClientSecret = nameValue[QueryKeyMenu.clientSecret.ToString()],
                RedirctUrl   = nameValue[QueryKeyMenu.redirctUrl.ToString()],
                ReturnUrl    = nameValue[QueryKeyMenu.returnUrl.ToString()],
                State        = nameValue[QueryKeyMenu.state.ToString()],
                Scope        = nameValue[QueryKeyMenu.scope.ToString()]
            };

            //验证逻辑
            //获取servernumber
            var oAuthServiceDto = OAuthService.GetOAuthServiceDtoByClientSecret(validateDto.ClientSecret);

            if (oAuthServiceDto != null)
            {
                //验证是否存在SSO
                bool isExist = OAuthService.IsExist(oAuthServiceDto.ServiceNumber, validateDto.ClientSecret);
                if (isExist)
                {
                    loginInfo.ServiceNumber = oAuthServiceDto.ServiceNumber;
                    loginInfo.Password      = System.Web.Security.FormsAuthentication.
                                              HashPasswordForStoringInConfigFile(loginInfo.Password, "MD5").ToLower();
                    //验证该用户是否存在
                    bool isLogin = LoginService.Validate(validateDto.State, validateDto.Scope, loginInfo);
                    if (isLogin)
                    {
                        //转跳到Redirect页面
                        string url = UrlString(oAuthServiceDto.DomainName, oAuthServiceDto.RedirectUri, validateDto.State,
                                               loginInfo.Code, validateDto.ReturnUrl);
                        return(Redirect(url));
                    }
                    else
                    {
                        message = "该用户不存在";
                    }
                }
                else
                {
                    message = "系统码与密钥不一致";
                }
            }
            else
            {
                message = "该系统未注册统一系统管理.";
            }
            TempData["ValidRedirect"] = true;//不是盗链
            return(Redirect(string.Format(curLogin, nameValue, message)));
        }
Пример #8
0
        public async Task <LoginResultEnum> LoginCookie(LoginInfoDto loginInfo)
        {
            SignInResult result =
                await _signInManager.PasswordSignInAsync(loginInfo.Username, loginInfo.Password, false, false);

            if (result == SignInResult.Failed)
            {
                return(LoginResultEnum.WrongUsernamePassword);
            }
            if (result == SignInResult.Success)
            {
                return(LoginResultEnum.Success);
            }
            return(LoginResultEnum.Unknown);
        }
Пример #9
0
        public async Task <IActionResult> GetToken([FromBody] LoginInfoDto loginInfoDto)
        {
            SOApiResult <bool> resultLogin = await _userApiService.IsSucceedLogin(loginInfoDto);

            if (resultLogin.IsSucceed)
            {
                SOApiResult <string> result = await _userApiService.GenerateToken(loginInfoDto.UserName);

                if (result.IsSucceed)
                {
                    return(Ok(result.ReturnedDataJSON));
                }
                return(BadRequest(result.Message));
            }
            return(BadRequest(resultLogin.Message));
        }
Пример #10
0
        /// <summary>
        /// 到权限获取是否存在
        /// 目前先写SQL吧
        /// 分为各种系统不同的登录验证
        /// </summary>
        /// <param name="state"></param>
        /// <param name="scope"></param>
        /// <param name="loginInfo"></param>
        /// <returns></returns>
        public bool Validate(string state, string scope, LoginInfoDto loginInfo)
        {
            bool reuslt = false;

            //先假验证成功,需要权限系统接口,
            //等表建立,先写SQL
            //这块以后写入到权限模块
            try
            {
                var employeeInfo = this.CacheClient.GetCache <IEnumerable <EmployeeInfoDto> >
                                       (ApplicationConstant.EMPLOYEEKEY);
                //TODO:目前的补偿措施,等待schedual
                if (employeeInfo == null)
                {
                    employeeInfo = GetEmployeeInfos();
                }

                if (employeeInfo != null)
                {
                    var query = employeeInfo.FirstOrDefault(m => m.UserName == loginInfo.EmployeeID &&
                                                            m.Password == loginInfo.Password);
                    if (query != null)
                    {
                        Token = new TokenDto()
                        {
                            AssessToken = query.Token()
                        };

                        AccessToken = new AccessTokenDto
                        {
                            AccessToken = MD5Hash(Serializer.ToJson(query))
                        };

                        reuslt = true;
                    }
                    if (reuslt)
                    {
                        SaveValidate(state, scope, loginInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(reuslt);
        }
Пример #11
0
        public async Task <IActionResult> Login([FromBody] LoginInfoDto loginInfo)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Login information is not valid."));
            }

            var auth = await _authService.Authenticate(loginInfo.Username, loginInfo.Password);

            if (!auth)
            {
                return(Unauthorized());
            }

            var token = _tokenService.GenerateToken();

            return(Ok(token));
        }
Пример #12
0
        public async Task <LoginResultDto> Login(LoginInfoDto loginInfo)
        {
            var result = new LoginResultDto();

            UserEntity user = await _userManager.FindByNameAsync(loginInfo.Username);

            if (user == null)
            {
                result.Result = LoginResultEnum.WrongUsernamePassword;
            }
            else if (!await _userManager.CheckPasswordAsync(user, loginInfo.Password))
            {
                result.Result = LoginResultEnum.WrongUsernamePassword;
            }
            else
            {
                result.Result = LoginResultEnum.Success;
                result.Token  = _tokenService.GetToken(user);
            }

            return(result);
        }
Пример #13
0
        public async Task <SOApiResult <bool> > IsSucceedLogin(LoginInfoDto loginInfoDto)
        {
            S_USER user = await Repository.SysApi_UserManager.FindByNameAsync(loginInfoDto.UserName);

            if (user == null)
            {
                //Log Here
                return(new SOApiErrorResult <bool>("User not found"));
            }
            SignInResult resultLogin = await Repository.SysApi_SignInManager
                                       .PasswordSignInAsync(
                user,
                loginInfoDto.Password,
                loginInfoDto.IsRemember,
                false);

            if (resultLogin.Succeeded)
            {
                return(new SOApiSuccessResult <bool>());
            }
            return(new SOApiErrorResult <bool>("Login failed"));
        }
Пример #14
0
        public async Task <JsonResult> Verify(LoginInfoDto logoInfo)
        {
            ResponseTemplate response = new ResponseTemplate();

            if (string.IsNullOrEmpty(logoInfo.VerificationCode) || logoInfo.VerificationCode != HttpContext.Session.GetString("VerificationCode"))
            {
                response.Message = "验证码错误!";
                return(Json(response));
            }
            var manager = await _db.Manager.SingleOrDefaultAsync(m => m.ManagerName == logoInfo.UserName);

            if (manager != null && manager.ManagerPassword == logoInfo.PassWord)
            {
                response.Success = true;
                response.Message = "登录成功!";
                HttpContext.Session.SetString("Token", manager.ManagerName);
            }
            else
            {
                response.Message = "账号或密码无效!";
            }
            return(Json(response));
        }
        public async Task <IActionResult> Login(LoginInfoDto loginInfoDto)
        {
            var user = await _userManager.FindByNameAsync(loginInfoDto.UserName);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect!" }));
            }
            var check = await _userInformationService.CheckInitializedInfo(user.Id);

            if (!check)
            {
                await _userInformationService.AddWithEmptyInfo(user.Id, "");

                await _unitOfWork.Commit();
            }
            var userInfo = await _userInformationService.GetOne(user.Id);

            var result = await _authService.AuthenticateUser(user, loginInfoDto.Password, userInfo.IsBlocked);

            switch (result)
            {
            case AuthenticateUserResult.Invalid:
                return(BadRequest(new { message = "Username or password is incorrect!" }));

            case AuthenticateUserResult.Blocked:
                return(Forbid());

            case AuthenticateUserResult.Succeeded:
                var token = await _tokenService.GenerateToken(user, _appSetting.JwtSecret);

                return(Ok(new { token, user.Id }));

            default:
                return(NotFound());
            }
        }
Пример #16
0
        public async Task <IActionResult> CreateToken([FromBody] LoginInfoDto loginInfo)
        {
            if (String.IsNullOrWhiteSpace(loginInfo.Login) || String.IsNullOrWhiteSpace(loginInfo.Password))
            {
                return(BadRequest());
            }

            var user = await _usersRepository.GetByLoginAsync(loginInfo.Login);

            if (user == null)
            {
                return(NotFound());
            }

            if (!_passwordHasher.VerifyPassword(loginInfo.Password, user.PasswordHash, user.Salt))
            {
                return(BadRequest("Invalid credidentials"));
            }

            Claim[] claims = GetClaims(user);
            string  token  = GetToken(claims);

            return(Ok(token));
        }
Пример #17
0
        public async Task <SOApiResult <string> > GetToken(LoginInfoDto loginInfoDto)
        {
            string urlPath = "/UserApi/GetToken";

            return(await SOApiHelper.ExecutePostMethodAnonymous <string>(_httpClientFactory, urlPath, loginInfoDto));
        }
Пример #18
0
 public async Task <LoginResultDto> Login(LoginInfoDto loginInfo)
 {
     Validate();
     return(await _accountService.Login(loginInfo));
 }
Пример #19
0
 public async Task <SOApiResult <bool> > IsSucceedLogin(LoginInfoDto loginInfoDto)
 {
     return(await _repository.SUSER_REPOSITORY.IsSucceedLogin(loginInfoDto));
 }
Пример #20
0
 public Task <LoginResultEnum> Post([FromBody] LoginInfoDto loginInfo)
 {
     Validate();
     return(_accountService.LoginCookie(loginInfo));
 }
Пример #21
0
        /// <summary>
        /// 调用webservice登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>

        public LoginInfoDto SSOLogin(string userName, string pwd)
        {
            string       callBackStr = null;
            LoginInfoDto model       = new LoginInfoDto();

            try
            {
                callBackStr = GetUserInfo(userName, pwd);
                //MarketingSystem.Common.LogManager.WriteLog(MarketingSystem.Common.LogFile.Trace, "接口返回信息:" + userName + "|" + pwd + " BEGIN:" + callBackStr);
            }
            catch
            {
                model = new LoginInfoDto()
                {
                    Code = 0, Msg = "访问登录接口失败!"
                };
            }

            if (!string.IsNullOrEmpty(callBackStr))
            {
                //  Dictionary<string,int>
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(callBackStr);
                string content = xmlDoc.DocumentElement.InnerText;

                if (!string.IsNullOrEmpty(content))
                {
                    UserInfoDto loginInfo = new UserInfoDto();
                    string[]    spltStr   = content.Split('|');

                    try
                    {
                        if (spltStr[0] == "0")
                        {
                            string[] userInfo = spltStr[1].Split(',');
                            loginInfo.GroupID    = userInfo[4];
                            loginInfo.LoginName  = userInfo[0];
                            loginInfo.LoginNo    = userInfo[1];
                            loginInfo.PhoneNo    = userInfo[2];
                            loginInfo.Department = userInfo[3];
                            if (userInfo[3] == "null" || userInfo[3] == "" || loginInfo.GroupID == "null" || loginInfo.GroupID == "")
                            {
                                model = new LoginInfoDto()
                                {
                                    Code = 0, Msg = "请核实该网点是否有效!"
                                };
                            }
                            else
                            {
                                loginInfo.MenuList = GetMenuList(spltStr[2]);
                            }

                            model = new LoginInfoDto()
                            {
                                Code = 1, Msg = "", User = loginInfo
                            };
                        }
                    }
                    catch (Exception ex)
                    {
                        model = new LoginInfoDto()
                        {
                            Code = 0, Msg = "抱歉,登陆失败!"
                        };
                        //MarketingSystem.Common.LogManager.WriteLog(LogFile.Trace, "Login" + ex.StackTrace + "\n" + ex.Message + "\n line:" + ex.Source);
                    }
                }
                else
                {
                    model = new LoginInfoDto()
                    {
                        Code = 0, Msg = "登录接口返回数据为空!"
                    };
                }

                // string json = Common.JsonHelper.Object2Json(model);

                // Response.Write(json);
            }
            return(model);
        }