Captcha Validation Setup
This article explains how to use your application's backend to verify the user's response to the Telerik UI Captcha.
Always generate the CAPTCHA and apply the validation on the server-side of your application. This approach guarantees that no programs or bots can access the values of the CAPTCHA on the client-side via JavaScript and then bypass the validation.
To proceed with the tutorial below, make sure that the Captcha Server-side Provider is added and referenced in your project.
Getting Started
To generate CAPTCHAs and validate the user's input, the Telerik UI Captcha depends on the following main options:
Handler
—Sets the URL handler, function, or action configuration that fetches the generated image.AudioHandler
—Sets the URL handler, function, or action configuration that fetches the generated audio.ValidationHandler
—Sets the URL handler, function, or action configuration that can validate the captcha remotely.
-
To generate a new CAPTCHA, use the
GetNewCaptcha()
method of theCaptchaHelper
. Save the CAPTCHA to a Session.Razorprivate void GenerateNewCaptcha() { CaptchaImage captchaImage = SetCaptchaImage(); ViewData["Captcha"] = "./shared/UserFiles/captcha/" + captchaImage.UniqueId + ".png"; ViewData["CaptchaID"] = captchaImage.UniqueId; } private CaptchaImage SetCaptchaImage() { CaptchaImage newCaptcha = CaptchaHelper.GetNewCaptcha(); MemoryStream audio = CaptchaHelper.SpeakText(newCaptcha); using (FileStream file = new FileStream(Path.Combine(CaptchaPath, newCaptcha.UniqueId + ".wav"), FileMode.Create, FileAccess.Write)) { audio.WriteTo(file); } var image = CaptchaHelper.RenderCaptcha(newCaptcha); image.Save(Path.Combine(CaptchaPath, newCaptcha.UniqueId + ".png"), ImageFormat.Png); var key = newCaptcha.UniqueId; var value = JsonConvert.SerializeObject(newCaptcha); HttpContext.Session.SetString("captcha_" + key, value); return newCaptcha; }
Generate the CAPTCHA in the
ActionMethod
that returns the Razor View. If the CAPTCHA is used in multiple Razor Views, generate it in the Controller's constructor.C#public ActionResult Index(UserViewModel user, CaptchaModel captchaModel) { if (string.IsNullOrEmpty(captchaModel.CaptchaID)) { GenerateNewCaptcha(); return View(); } else { string text = GetCaptchaText(captchaModel.CaptchaID); if (text == captchaModel.Captcha.ToUpperInvariant()) { ModelState.Clear(); GenerateNewCaptcha(); } } return View(user); }
-
Introduce the Telerik UI Captcha in a Razor View:
Razor@(Html.Kendo().Captcha() .Name("Captcha") .CaptchaImage((string)ViewData["Captcha"]) .CaptchaId((string)ViewData["CaptchaID"]) .DataCaptchaField("Captcha") // The field containing the Captcha from the server-side should be called Captcha. .DataCaptchaIdField("CaptchaID") // The field containing the Captcha's ID from the server-side should be called CaptchaID. .Handler(handler => handler.Action("Reset", "Captcha")) .AudioHandlerFunction("audioHandler") .ValidationHandler(handler => handler.Action("Validate", "Captcha")) .ValidateOnBlur(true) )
-
Add the server-side handlers for the Captcha:
Razorpublic ActionResult Reset() { CaptchaImage newCaptcha = SetCaptchaImage(); return Json(new CaptchaModel { Captcha = "./shared/UserFiles/captcha/" + newCaptcha.UniqueId + ".png", CaptchaID = newCaptcha.UniqueId }); } public ActionResult Validate(CaptchaModel model) { string text = GetCaptchaText(model.CaptchaID); return Json(text == model.Captcha.ToUpperInvariant()); }
If you omit to set the
CaptchaImage
andCaptchaId
options, the widget will not have an image preloaded. When initialized, it will fetch the image from theHandler()
option.Instead of the ViewData, you could use the page's model.
Form Integration
The Telerik UI Captcha for ASP.NET Core prevents automated programs from performing tasks such as form submissions. If the user does not enter the text from the CAPTCHA image correctly, a validation error is shown and the form submission is aborted.
-
Create a form and add the Telerik UI Captcha.
Razor@model UserViewModel <form id="form" method="POST"> @(Html.Kendo().TextBoxFor(m => m.UserName)) @(Html.Kendo().TextBoxFor(m => m.FirstName)) @(Html.Kendo().TextBoxFor(m => m.LastName)) @(Html.Kendo().Captcha() .Name("Captcha") .CaptchaImage((string)ViewData["Captcha"]) .CaptchaId((string)ViewData["CaptchaID"]) .DataCaptchaField("Captcha") .DataCaptchaIdField("CaptchaID") .Handler(handler => handler.Action("Reset", "Captcha")) .AudioHandlerFunction("audioHandler") .ValidationHandler(handler => handler.Action("Validate", "Captcha")) ) @(Html.Kendo().Button() .Name("Submit") .Content("Submit") .HtmlAttributes(new { type="submit" }) ) </form>
-
Instantiate a Telerik UI Validator from the form inside the document.ready() event.
Razor<script> $(document).on("ready", function () { $("#form").kendoValidator(); }); function audioHandler(args) { args.success("./shared/UserFiles/captcha/" + args.data.CaptchaID + ".wav"); } </script>
If the state of the Telerik UI Captcha is invalid, the Validator prevents the form submission and shows an error message to the user.