private void ValidateCaptcha(string userEnteredCaptchaCode, string captchaId) { var captcha = new SimpleCaptcha(); bool isHuman = captcha.Validate(userEnteredCaptchaCode, captchaId); if (!isHuman) { throw new InvalidOperationException("Incorrect Captcha characters!"); } }
public async Task <AuthenticationLoginModel> LoginAsync(AuthenticationLoginRequest rq) { if (rq.CaptchaNeeded) { var captcha = new SimpleCaptcha(); bool isHuman = captcha.Validate(rq.UserEnteredCaptchaCode, rq.CaptchaId); if (!isHuman) { return new AuthenticationLoginModel { Successful = false, Message = "Incorrect Captcha characters!" } } ; } //ValidateCaptcha(rq.UserEnteredCaptchaCode, rq.CaptchaId); // Handle user ApplicationUser user = await _userMgr.FindByNameAsync(rq.Email); if (user == null) { return new AuthenticationLoginModel { Successful = false, Message = "User not found" } } ; if (await _userMgr.IsLockedOutAsync(user)) { return new AuthenticationLoginModel { Successful = false, Message = "User is locked out" } } ; // Handle signin SignInResult result = await _signInMgr.PasswordSignInAsync(rq.Email, rq.Password, true, true); if (!result.Succeeded) { return new AuthenticationLoginModel { Successful = false, Message = "Password is incorrect" } } ; // Handle roles IList <string> roles = await _userMgr.GetRolesAsync(user); return(new AuthenticationLoginModel { Successful = true, Message = "Logged in successfully", AccessToken = GenerateJwt(user, roles) }); }
public IActionResult CheckCaptcha(Models.Captcha value) { if (value == null) { return(BadRequest()); } var userEnteredCaptchaCode = value.UserEnteredCaptchaCode; var captchaId = value.CaptchaId; var ticTacToeCaptcha = new SimpleCaptcha(); var isHuman = ticTacToeCaptcha.Validate(userEnteredCaptchaCode, captchaId); return(Ok(isHuman)); }
public IHttpActionResult ValidateCaptcha(string user, string userId) { if (ModelState.IsValid) { SimpleCaptcha captchaCode = new SimpleCaptcha(); bool isHuman = captchaCode.Validate(user, userId); return(Ok(isHuman)); } else { return(BadRequest()); } }
public bool Ishuman(string Id, string Code) { if (string.IsNullOrEmpty(Id)) { return(false); } // create a captcha instance to be used for the captcha validation SimpleCaptcha simpleCaptcha = new SimpleCaptcha(); return(simpleCaptcha.Validate(Code, Id)); // return false; }
public async Task <IActionResult> Login([FromBody] LoginModel loginModel) { if (!ModelState.IsValid) { return(Ok(ServiceResult.Error(ModelState))); } // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(loginModel.UserEnteredCaptchaCode, loginModel.CaptchaId); if (isHuman == false) { return(Ok(ServiceResult.Error("کد امنیتی اشتباه است"))); } var appUser = userManager.Users.Include(c => c.PhoneNumbers).FirstOrDefault(c => c.UserName.Equals(loginModel.UserName) || c.NationalCode.Equals(loginModel.UserName) || c.PhoneNumbers.Any(i => i.PhoneNumber.Equals(loginModel.UserName))); if (appUser == null) { return(Ok(ServiceResult.Error("کاربری یافت نشد"))); } var verifyPass = userManager.PasswordHasher .VerifyHashedPassword(appUser, appUser.PasswordHash, loginModel.Password); // policy //appUser.PhoneNumbers.Any(c=>c.IsPrimary && c.IsConfirm) if (verifyPass == PasswordVerificationResult.Failed) { return(Ok(ServiceResult.Error("کاربری یافت نشد"))); } await signInManager.SignInAsync(appUser, true, JwtBearerDefaults.AuthenticationScheme); return(Ok(ServiceResult <string> .Okay(GenerateJwtToken(appUser)))); }
public async Task <IActionResult> Register([FromBody] RegisterModel registerModel) { if (!ModelState.IsValid) { return(Ok(ServiceResult.Error(ModelState))); } // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(registerModel.UserEnteredCaptchaCode, registerModel.CaptchaId); if (isHuman == false) { return(Ok(ServiceResult.Error("کد امنیتی اشتباه است"))); } // validation unique pjoneNumber and nationalCode if (userManager.Users.Any(c => c.NationalCode.Equals(registerModel.NationalCode))) { return(Ok(ServiceResult.Error("کد ملی متعلق به شخص دیگری است"))); } if (_userPhoneNumberRepository .AsQueryable() .Any(c => c.PhoneNumber.Equals(registerModel.PhoneNumber))) { return(Ok(ServiceResult.Error("شماره همراه متعلق به شخص دیگری است"))); } var result = await userManager.CreateAsync(new AppIdentityUser { NationalCode = registerModel.NationalCode, UserName = registerModel.UserName, IsAdmin = false }, registerModel.Password); if (result.Succeeded) { var appUser = await userManager.FindByNameAsync(registerModel.UserName); var activationCode = new Random().Next(1000, 9999); var verificationTime = _settingRepository.AsQueryable() .FirstOrDefault(c => c.Key.Equals(Enums.Setting.VerificationTime.ToString())); int verificationTimeMin = 3; if (verificationTime != null) { verificationTimeMin = Convert.ToInt32(verificationTime.Value); } _userPhoneNumberRepository.Create(new UserPhoneNumber { IsConfirm = false, IsPrimary = true, PhoneNumber = registerModel.PhoneNumber, UserId = appUser.Id, ActivationCode = activationCode, ActivationCodeExpireDate = DateTime.Now.AddMinutes(verificationTimeMin) }); new SmsProvider.SmsService().Send(registerModel.PhoneNumber, $"کد فعالسازی شما : {activationCode}"); return(Ok(ServiceResult <int> .Okay(verificationTimeMin))); } var errors = result.Errors.Select(c => c.Description).ToList(); return(Ok(ServiceResult.Error(errors))); }
public async Task <IActionResult> Login([FromBody] SysAdminLogin parm) { var res = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; try { //获得公钥私钥,解密 var rsaKey = await _cache.GetAsync <List <string> >($"LOGINKEY:{parm.lid}"); if (rsaKey == null) { res.message = "登录失败,请刷新浏览器再次登录"; return(Ok(res)); } //Ras解密密码 var ras = new RSACrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(_config[KeyHelper.LOGINCOUNT]); //获得登录次数和过期时间 var loginConfig = await _cache.GetAsync <SysAdminLoginConfig>(KeyHelper.LOGINCOUNT) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { res.message = "您的登录以超过设定次数,请稍后再次登录~"; return(Ok(res)); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #region 验证码 var captcha = new SimpleCaptcha(); if (!captcha.Validate(parm.code, parm.cid)) { res.message = "验证码错误"; res.statusCode = (int)ApiEnum.ParameterError; return(Ok(res)); } #endregion //查询登录结果 var dbres = await _adminService.LoginAsync(parm); if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(_config[KeyHelper.LOGINDELAYMINUTE]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); res.message = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(Ok(res)); } //记录登录次数,保存到session await _cache.SetAsync(KeyHelper.LOGINCOUNT, loginConfig); //提示用户错误和登录次数信息 res.message = dbres.message; return(Ok(res)); } var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.PrimarySid, user.IsSystem.ToString()), new Claim(ClaimTypes.Sid, user.Guid), new Claim(ClaimTypes.Role, "授权用户"), new Claim(ClaimTypes.Name, user.TrueName), new Claim(ClaimTypes.WindowsAccountName, user.LoginName), new Claim(ClaimTypes.UserData, user.UpLoginDate.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity); ////如果保存用户类型是Session,则默认设置cookie退出浏览器 清空 //if (_config[KeyHelper.LOGINSAVEUSER] == "Session") //{ // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties // { // AllowRefresh = false // }); //} //else //{ // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties // { // ExpiresUtc = DateTime.UtcNow.AddHours(_config.GetValue(KeyHelper.LOGINCOOKIEEXPIRES, 0.5D)), // IsPersistent = true, // AllowRefresh = false // }); //} //把权限存到缓存里 await _cache.SetAsync(KeyHelper.ADMINMENU + "_" + dbres.data.admin.Guid, dbres.data.menu); res.data = JwtHelper.IssueJWT(new TokenModel() { Uid = user.Guid, UserName = user.LoginName, Role = "Admin", TokenType = "Web" }); await _cache.RemoveAsync($"LOGINKEY:{parm.lid}"); await _cache.RemoveAsync(KeyHelper.LOGINCOUNT); #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Info", Message = "登录:" + parm.loginname, Callsite = "/fytadmin/login", IP = HttpContext.GetIP(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (CryptographicException) { res.message = "登录失败,请刷新浏览器重试"; res.statusCode = (int)ApiEnum.Error; return(Ok(res)); } catch (Exception ex) { var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { Guid = Guid.NewGuid().ToString(), Logged = DateTime.Now, Logger = LogEnum.LOGIN.GetEnumText(), Level = "Error", Message = "登录失败!" + ex.Message, Exception = ex.ToString(), Callsite = "/fytadmin/login", IP = HttpContext.GetIP(), User = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); res.message = "登录失败,请刷新浏览器重试"; res.statusCode = (int)ApiEnum.Error; return(Ok(res)); } res.statusCode = (int)ApiEnum.Status; return(Ok(res)); }