public void Validate() { if (skipRecaptcha) { recaptchaResponse = RecaptchaResponse.Valid; } else { RecaptchaValidator validator = new RecaptchaValidator(); validator.PrivateKey = privateKey; validator.RemoteIP = Page.Request.UserHostAddress; if (String.IsNullOrEmpty(RecaptchaChallengeValue) && String.IsNullOrEmpty(RecaptchaResponseValue)) { validator.Challenge = Context.Request.Form[RECAPTCHA_CHALLENGE_FIELD]; validator.Response = Context.Request.Form[RECAPTCHA_RESPONSE_FIELD]; } else { validator.Challenge = RecaptchaChallengeValue; validator.Response = RecaptchaResponseValue; } recaptchaResponse = validator.Validate(); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var valid = false; var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY]; var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY]; if (!string.IsNullOrEmpty(captchaChallengeValue) && !string.IsNullOrEmpty(captchaResponseValue)) { var captchaSettings = EngineContext.Current.Resolve <CaptchaSettings>(); if (captchaSettings.Enabled) { //validate captcha var captchaValidtor = new RecaptchaValidator { PrivateKey = captchaSettings.ReCaptchaPrivateKey, RemoteIP = filterContext.HttpContext.Request.UserHostAddress, Challenge = captchaChallengeValue, Response = captchaResponseValue }; var recaptchaResponse = captchaValidtor.Validate(); valid = recaptchaResponse.IsValid; } } //this will push the result value into a parameter in our Action filterContext.ActionParameters["captchaValid"] = valid; base.OnActionExecuting(filterContext); }
/// <summary> /// The validate. /// </summary> public void Validate() { if (this.skipRecaptcha) { this.recaptchaResponse = RecaptchaResponse.Valid; } else { var validator = new RecaptchaValidator { PrivateKey = this.privateKey, RemoteIP = Utils.GetClientIP() }; if (String.IsNullOrEmpty(this.RecaptchaChallengeValue) && String.IsNullOrEmpty(this.RecaptchaResponseValue)) { validator.Challenge = this.Context.Request.Form[RecaptchaChallengeField]; validator.Response = this.Context.Request.Form[RecaptchaResponseField]; } else { validator.Challenge = this.RecaptchaChallengeValue; validator.Response = this.RecaptchaResponseValue; } this.recaptchaResponse = validator.Validate(); } }
/// <summary> /// Called before the action method is invoked /// </summary> /// <param name="filterContext">Information about the current request and action</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { var captchaChallengeValue = filterContext.HttpContext.Request.Form[ChallengeFieldKey]; var captchaResponseValue = filterContext.HttpContext.Request.Form[ResponseFieldKey]; var captchaValidtor = new RecaptchaValidator { PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"], RemoteIP = filterContext.HttpContext.Request.UserHostAddress, Challenge = captchaChallengeValue, Response = captchaResponseValue }; var recaptchaResponse = captchaValidtor.Validate(); // this will push the result value into a parameter in our Action //filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid; //filterContext.RouteData.Values.Add("captchaValid", recaptchaResponse.IsValid); filterContext.RouteData.Values["captchaValid"] = recaptchaResponse.IsValid; base.OnActionExecuting(filterContext); // Add string to Trace for testing //filterContext.HttpContext.Trace.Write("Log: OnActionExecuting", String.Format("Calling {0}", filterContext.ActionDescriptor.ActionName)); }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var errors = new List <ValidationResult>(); var httpContext = HttpContext.Current; if (!httpContext.User.Identity.IsAuthenticated) // this means we are anonymous { var ipAddress = string.Empty; if (httpContext != null) { ipAddress = httpContext.Request.UserHostAddress; } var gRecaptchaResponse = httpContext.Request.Form["g-recaptcha-response"]; if ( !RecaptchaValidator.IsValidResponse(gRecaptchaResponse, ipAddress, FirmaWebConfiguration.RecaptchaPrivateKey, FirmaWebConfiguration.RecaptchaValidatorUrl, SitkaLogger.Instance.LogDetailedErrorMessage)) { errors.Add(new ValidationResult("Your Captcha response is incorrect.")); } } return(errors); }
/// <summary> /// The validate. /// </summary> public void Validate() { if (this.skipRecaptcha) { this.recaptchaResponse = RecaptchaResponse.Valid; } else { var validator = new RecaptchaValidator { PrivateKey = this.privateKey, RemoteIP = Utils.GetClientIP() }; if (this.RecaptchaResponseValue == null) { validator.Response = this.Context.Request.Form[RecaptchaResponseField]; } else { validator.Response = this.RecaptchaResponseValue; } this.recaptchaResponse = validator.Validate(); } }
public async Task <IActionResult> IndexAsync(ContactIndexViewModel model) { if (!RecaptchaValidator.IsRecaptchaValid(Request.Form["g-recaptcha-response"]) || model.TripCheck) { return(Ok()); } var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(); await _emailSender.SendEmailAsync(PlatformContactEmail, "Message From: " + model.Name, model.GetEmailMessage(ip)); return(RedirectToAction(nameof(Confirm))); }
public void BeforeSave_ValidateRecaptcha(Page page, Control control) { var err = ErrorFactory.CreateInstance(); try { var config = CreateRecaptchaConfigurationFromSystemOptions(); if (config.Enabled == false) { return; } var response = Config.Context.Request.Form[RecaptchaConstants.ResponseFormFieldName]; var result = RecaptchaValidator.Validate(config.PrivateKey, response); if (result == null) { err.Message = RecaptchaConstants.UnableToValidateMessage; } else if (result.IsSuccess == false) { err.Message = RecaptchaConstants.ValidationFailureMessage; } err.UserMessage = err.Message; } catch (Exception ex) { err = ErrorFactory.CreateInstance(ex); } finally { if (!String.IsNullOrWhiteSpace(err.Message)) { err.Number = (int)ErrorClass.ErrorNumber.ValidationFailed; err.Level = ErrorClass.ErrorLevel.Error; } if (UtilityFunctions.ER(err)) { Config.LastError = err; } else { Config.ClearLastError(); } } }
public static bool Validate(HttpContextBase context) { var request = context.Request; var validator = new RecaptchaValidator { PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"], RemoteIP = request.UserHostAddress, Challenge = request.Form[ChallengeFieldKey], Response = request.Form[ResponseFieldKey] }; RecaptchaResponse response = validator.Validate(); return(response.IsValid); }
public static bool IsCaptchaValid(this Controller controller, string privateKey) { string challenge = controller.HttpContext.Request.Form["recaptcha_challenge_field"]; string response = controller.HttpContext.Request.Form["recaptcha_response_field"]; if (string.IsNullOrEmpty(challenge) || string.IsNullOrEmpty(response)) { return(false); } var validator = new RecaptchaValidator { PrivateKey = privateKey, Challenge = challenge, Response = response, RemoteIP = controller.HttpContext.Request.UserHostAddress, }; return(validator.Validate().IsValid); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var captchaSettings = EngineContext.Current.Resolve <CaptchaSettings>(); if (captchaSettings.Enabled) { var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY]; var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY]; var captchaValidtor = new RecaptchaValidator { PrivateKey = captchaSettings.ReCaptchaPrivateKey, RemoteIP = filterContext.HttpContext.Request.UserHostAddress, Challenge = captchaChallengeValue, Response = captchaResponseValue }; var recaptchaResponse = captchaValidtor.Validate(); filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid; } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { Roadkill.Core.Mvc.Controllers.ControllerBase controller = filterContext.Controller as Roadkill.Core.Mvc.Controllers.ControllerBase; if (controller != null) { SiteSettings siteSettings = controller.SettingsService.GetSiteSettings(); if (siteSettings.IsRecaptchaEnabled) { string challengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_KEY]; string responseValue = filterContext.HttpContext.Request.Form[RESPONSE_KEY]; RecaptchaValidator validator = new RecaptchaValidator(); validator.PrivateKey = siteSettings.RecaptchaPrivateKey; validator.RemoteIP = filterContext.HttpContext.Request.UserHostAddress; validator.Challenge = challengeValue; validator.Response = responseValue; RecaptchaResponse validationResponse = validator.Validate(); filterContext.ActionParameters["isCaptchaValid"] = validationResponse.IsValid; } } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { ILog log = LogManager.GetLogger(typeof(CaptchaValidationFilter)); bool isValid = false; bool bSignupSkipCaptcha = (filterContext.ActionDescriptor.ActionName == "SignUp") && (filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "Account") && ( !filterContext.ActionParameters.ContainsKey("isInCaptchaMode") || (filterContext.ActionParameters["isInCaptchaMode"].ToString() != "True") ); log.DebugFormat("sign up skip captcha: {0}", bSignupSkipCaptcha ? "yes" : "no"); bool bBrokerSignupSkipCaptcha = false; if (!bSignupSkipCaptcha) { log.DebugFormat("sign up skip captcha: {0}", bSignupSkipCaptcha ? "yes" : "no"); bBrokerSignupSkipCaptcha = (filterContext.ActionDescriptor.ActionName == "Signup") && (filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "BrokerAccount") && ( !filterContext.ActionParameters.ContainsKey("IsCaptchaEnabled") || (filterContext.ActionParameters["IsCaptchaEnabled"].ToString() != "1") ); log.DebugFormat("broker sign up skip captcha: {0}", bBrokerSignupSkipCaptcha ? "yes" : "no"); } // if if (bSignupSkipCaptcha || bBrokerSignupSkipCaptcha) { isValid = true; } else { switch (CurrentValues.Instance.CaptchaMode.Value) { case "off": log.Debug("Captcha off mode"); isValid = true; break; case "simple": log.Debug("Simple Captcha mode"); isValid = filterContext.Controller.IsCaptchaValid(ErrorMessage); break; case "reCaptcha": log.Debug("re Captcha mode"); var validator = new RecaptchaValidator { PrivateKey = PrivateKey, RemoteIP = filterContext.HttpContext.Request.UserHostAddress, Challenge = filterContext.HttpContext.Request.Form[ChallengeFieldKey], Response = filterContext.HttpContext.Request.Form[ResponseFieldKey] }; isValid = validator.Validate().IsValid; break; } } // if filterContext.Controller.ViewData.ModelState.Clear(); log.DebugFormat("captcha is {0}", isValid ? "valid" : "invalid"); if (!isValid) { filterContext.Controller.ViewData.ModelState.AddModelError("", ErrorMessage); } base.OnActionExecuting(filterContext); } // OnActionExecuting
public ReCaptchaValidator(IConfigurationSource configSource) { _configSource = configSource; _recaptchaValidator = new RecaptchaValidator(); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); GoogleRecaptchaSiteKey = Environment.GetEnvironmentVariable("google_recaptcha_site_key"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (!RecaptchaValidator.IsRecaptchaValid(Request.Form["g-recaptcha-response"]) || Input.TripCheck) { ModelState.AddModelError(string.Empty, "Captcha invalid"); return(Page()); } if (ModelState.IsValid) { var user = new VollyV3User { UserName = Input.Email, Email = Input.Email, CreatedDateTime = DateTime.Now }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", ComposeEmailMessage(callbackUrl)); await _userManager.AddToRoleAsync(user, Enum.GetName(typeof(Role), Role.Volunteer)); if (Input.IsOrganizationAdministrator) { await _userManager.AddToRoleAsync(user, Enum.GetName(typeof(Role), Role.OrganizationAdministrator)); } if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(Page()); }
/// <summary> /// Creates a new ReCaptchValidator object. /// </summary> public ReCaptchaValidator() { recaptchaValidator = new RecaptchaValidator(); }
/// <summary> /// The validate. /// </summary> public void Validate() { if (this.skipRecaptcha) { this.recaptchaResponse = RecaptchaResponse.Valid; } if (this.recaptchaResponse != null) { return; } var validator = new RecaptchaValidator { SecretKey = this.SecretKey, RemoteIP = this.Page.Request.GetUserRealIPAddress(), Response = this.Context.Request.Form["g-recaptcha-response"] }; try { this.recaptchaResponse = validator.Validate(); } catch (ArgumentNullException exception) { this.recaptchaResponse = null; this.errorMessage = exception.Message; } }
public ActionResult Save(bool enableCaptcha, string thankyouMessage, string redirectUrl, string emailAddress, string widgetTitle) { // Validate captcha if (enableCaptcha) { var captchaChallengeValue = Request.Form["recaptcha_challenge_field"]; var captchaResponseValue = Request.Form["recaptcha_response_field"]; if (!string.IsNullOrEmpty(captchaChallengeValue)) { if (string.IsNullOrEmpty(captchaResponseValue)) { throw new ArgumentException(RecaptchaResponse.InvalidResponse.ErrorMessage); } var captchaValidator = new RecaptchaValidator { PrivateKey = captchaSettings.PrivateKey, RemoteIP = Request.UserHostAddress, Challenge = captchaChallengeValue, Response = captchaResponseValue }; var validateResult = captchaValidator.Validate(); if (!validateResult.IsValid) { throw new ArgumentException(validateResult.ErrorMessage); } } } var values = Request.Form.AllKeys.ToDictionary(key => key, key => (object)Request.Form[key]); // Remove some items values.Remove("EnableCaptcha"); values.Remove("ThankyouMessage"); values.Remove("RedirectUrl"); values.Remove("EmailAddress"); values.Remove("WidgetTitle"); values.Remove("X-Requested-With"); var subject = widgetTitle; var body = new StringBuilder(); body.Append(subject); body.Append("<br/>"); body.Append("<table style=\"width: 100%; border-collapse: collapse; border-spacing: 0;\">"); foreach (var value in values) { body.Append("<tr>"); body.Append("<td style=\"border-color: #DDDDDD; border-style: solid; border-width: 1px; color: #000000; font-size: 12px; padding: 7px;\">"); body.Append(value.Key); body.Append("</td>"); body.Append("<td style=\"border-color: #DDDDDD; border-style: solid; border-width: 1px; color: #000000; font-size: 12px; padding: 7px;\">"); body.Append(value.Value); body.Append("</td>"); } body.Append("</table>"); emailSender.Send(subject, body.ToString(), emailAddress); var result = new AjaxResult(); if (!string.IsNullOrEmpty(thankyouMessage)) { result.Alert(thankyouMessage); } result.Redirect(!string.IsNullOrWhiteSpace(redirectUrl) ? redirectUrl : Url.Content("~/")); return(result); }
public ActionResult Register(string username, string email, string password, string confirmPassword) { // Basic parameter validation if (String.IsNullOrEmpty(username)) { ModelState.AddModelError("username", "You must specify a username.", username); } if (String.IsNullOrEmpty(email)) { ModelState.AddModelError("email", "You must specify an email address.", email); } if (password == null || password.Length < this.Provider.MinRequiredPasswordLength) { string passwordError = String.Format(CultureInfo.CurrentCulture, "You must specify a new password of {0} or more characters.", this.Provider.MinRequiredPasswordLength); ModelState.AddModelError("password", passwordError, password); } if (!String.Equals(password, confirmPassword, StringComparison.Ordinal)) { ModelState.AddModelError("_FORM", "The new password and confirmation password do not match."); } // We don't check the captcha if running localhost and no challenge was given if (this.Request.UserHostAddress == "127.0.0.1" && this.Request.Form["recaptcha_challenge_field"] != null) { // Check the captcha response RecaptchaValidator humanValidator = new RecaptchaValidator(); humanValidator.PrivateKey = ConfigurationManager.AppSettings["RecaptchaPrivateKey"]; humanValidator.RemoteIP = this.Request.UserHostAddress; humanValidator.Challenge = this.Request.Form["recaptcha_challenge_field"]; humanValidator.Response = this.Request.Form["recaptcha_response_field"]; RecaptchaResponse humanResponse = humanValidator.Validate(); if (!humanResponse.IsValid) { Dictionary <string, object> props = new Dictionary <string, object> { { "PrivateKey", humanValidator.PrivateKey }, { "RemoteIP", humanValidator.RemoteIP }, { "Challenge", humanValidator.Challenge }, { "Response", humanValidator.Response }, { "IsValid", humanResponse.IsValid }, { "ErrorCode", humanResponse.ErrorCode } }; Logger.Write("Failed reCAPTCHA attempt", "Controller", 200, 0, TraceEventType.Verbose, "Failed reCAPTCHA attempt", props); ModelState.AddModelError("recaptcha", "reCAPTCHA failed to verify", humanValidator.Response); } } if (ViewData.ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; CosmoMongerMembershipUser newUser = (CosmoMongerMembershipUser)this.Provider.CreateUser(username, password, email, null, null, false, null, out createStatus); if (newUser != null) { return(RedirectToAction("SendVerificationCode", new RouteValueDictionary(new { username = username }))); } else { ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form return(View()); }