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.private 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.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); }
public class CaptchaModel { private string _captchaValue; public string Captcha { get { return string.IsNullOrEmpty(_captchaValue) ? "" : _captchaValue; } set { _captchaValue = value; } } public string CaptchaID { get; set; } }
-
Introduce the Telerik UI Captcha in a Razor View:
@(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) )
<kendo-captcha name="Captcha" captcha-image="@ViewData["Captcha"]" captcha-id="@ViewData["CaptchaID"]" datacaptchafield="Captcha" datacaptchaidfield="CaptchaID" validate-on-blur="true"> <handler url="@Url.Action("Reset", "Captcha")" /> <audio-handler function-handler="audioHandler" /> <validation-handler url="@Url.Action("Validate", "Captcha")" /> </kendo-captcha>
<script> function audioHandler(args) { args.success("@Url.Action("Audio")?captchaId=" + args.data.captchaId); } </script>
-
Add the server-side handlers for the Captcha:
public 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.
@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>
@model UserViewModel <form id="form" method="POST"> <kendo-textbox for="@Model.UserName"></kendo-textbox> <kendo-textbox for="@Model.FirstName"></kendo-textbox> <kendo-textbox for="@Model.LastName"></kendo-textbox> <kendo-captcha name="Captcha" captcha-image="@ViewData["Captcha"]" captcha-id="@ViewData["CaptchaID"]" datacaptchafield="Captcha" datacaptchaidfield="CaptchaID"> <handler url="@Url.Action("Reset", "Captcha")" /> <audio-handler function-handler="audioHandler" /> <validation-handler url="@Url.Action("Validate", "Captcha")" /> </kendo-captcha> <kendo-button name="Submit" type="submit"> Submit </kendo-button> </form>
-
Instantiate a Telerik UI Validator from the form inside the document.ready() event.
<script> $(document).on("kendoReady", 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.