Skip to main content

Sitecore 9 Forms :  Alphanumeric Captcha

Sitecore 9 Forms :  Alphanumeric Captcha

As you know Recaptcha is not available on Sitecore 9.0.1 and Sitecore 9.0.2 forms, so I thought to create custom Google Recaptcha but my issue was Google Recaptcha was not working properly on Internet Explorer as it was asking 10 to 15 times to verify which is very frustrating, at the same time it was working for another browser so I thought to create custom Alphanumeric captcha as per client requirement.

In previous blog, we have checked how to create Google reCaptcha field. Now we are going to create Alphanumeric Captcha using below steps:
  • Create new viewmodel class AlphaNumericViewModel.cs
[Serializable()]
    public class AlphaNumericViewModel : StringInputViewModel
    {
        protected override void InitItemProperties(Item item)
        {
            base.InitItemProperties(item);
        }
    }
  •  Create Controller AlphanumericCaptchaController.cs
public class AlphanumericCaptchaController: SitecoreController
       {
        public FileResult GetCaptchaImage()
        {
            string text = GetRandomText();
            System.Web.HttpContext.Current.Session["CAPTCHA"] = text;
            //first, create a dummy bitmap just to get a graphics object
            Image img = new Bitmap(1, 1);
            Graphics drawing = Graphics.FromImage(img);

            Font font = new Font("Arial", 15);
            //measure the string to see how big the image needs to be
            SizeF textSize = drawing.MeasureString(text, font);

            //free up the dummy image and old graphics object
            img.Dispose();
            drawing.Dispose();

            //create a new image of the right size
            img = new Bitmap((int)textSize.Width + 40, (int)textSize.Height + 20);
            drawing = Graphics.FromImage(img);

            Color backColor = Color.Black;
            Color textColor = Color.White;
            //paint the background
            drawing.Clear(backColor);

            //create a brush for the text
            Brush textBrush = new SolidBrush(textColor);

            drawing.DrawString(text, font, textBrush, 20, 10);

            drawing.Save();

            font.Dispose();
            textBrush.Dispose();
            drawing.Dispose();

            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            img.Dispose();

            return File(ms.ToArray(), "image/png");
        }
        private string GetRandomText()
        {
            StringBuilder randomText = new StringBuilder();
            string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz";
            Random r = new Random();
            for (int j = 0; j <= 5; j++)
            {
                randomText.Append(alphabets[r.Next(alphabets.Length)]);
            }
            return randomText.ToString();
        }
      }
  • Create new AlphaNumericCaptcha.cshtml file on this location “Website/Views/FormBuilder/FieldTemplates

@using Sitecore.ExperienceForms.Mvc.Html
@model <Namespace>.AlphaNumericViewModel

<div class="captcha-bar">
    <div class="captcha-td">
        <img src="@Url.Action("GetCaptchaImage", "AlphanumericCaptcha", new {id = new Random().Next()})" alt="captcha" id="recaptchaImage" class="captcha-text">
        <img src="../assets/ACUPublic/img/refresh.png" alt="" id="imgRefresh" class="refresh">
    </div>
    <div class="captcha-td"> <input type="text" id="@Html.IdFor(m => Model.Value)" name="@Html.NameFor(m => Model.Value)" class="@Model.CssClass captcha-input" value="@Model.Value"></div>
    @Html.ValidationMessageFor(m => Model.Value)
</div>



<script type="text/javascript">
    $("#imgRefresh").click(function (e) {
        $('#recaptchaImage').attr('src', '@Url.Action("GetCaptchaImage", "Recaptcha")' + '?' + new Date().getTime());
    });
</script>

  • Create new AlphaNumericCaptcha template on this location “/sitecore/templates/System/Forms/Fields”
  • Inherit below templates:

Alphanumeric Captcha

  • Switch to Core DB and create copy of this item /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings/SingleLineText with name “AlphaNumericCaptcha”
  • Now move again to Master DB.
  • Create new Field type here “/sitecore/system/Settings/Forms/Field Types/Security” with name “Alphanumeric Captcha”
  •  Fill below details:
a.      View Path: FieldTemplates/AlphaNumericCaptcha
b.      Model Type:  <Namespace>.AlphaNumericViewModel, <AssemblyName>
c.      Property Editor: Property Editor Settings/AlphaNumericCaptcha
d.      Field Template: Fields/AlphaNumericCaptcha

Custom Alphanumeric Validation

  •     Create new validation class AlpaNumericCaptchaValidator

public class AlpaNumericCaptchaValidator : ValidationElement<string>
    {
        public AlpaNumericCaptchaValidator(ValidationDataModel validationItem) : base(validationItem)
        {

        }
        public override void Initialize(object validationModel)
        {
            base.Initialize(validationModel);
        }
        public override ValidationResult Validate(object value)
        {
            if (value == null)
            {
                return new ValidationResult(FormatMessage("Invalid Captcha"));
            }


            if (HttpContext.Current.Session["CAPTCHA"] == null)
            {
                return new ValidationResult(FormatMessage("Session Expired"));
            }
            else
            {
                if (!value.Equals(HttpContext.Current.Session["CAPTCHA"].ToString()))
                {
                    return new ValidationResult(FormatMessage("Invalid Captcha"));
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
        }
        public override IEnumerable<ModelClientValidationRule> ClientValidationRules
        {
            get
            {
                var rule = new ModelClientValidationRule
                {
                    ErrorMessage = FormatMessage("Invalid"),
                };
                yield return rule;
            }
        }
}

  •      Go to this location “/sitecore/system/Settings/Forms/Validations” and create new validator “AlpaNumericCaptcha Validator”
  •      In Type field textbox add AlpaNumericCaptchaValidator.cs path like this: <Namespace>.AlpaNumericCaptchaValidator,<AssemblyName>
  •      Go to this location “/sitecore/system/Settings/Forms/Field Types/Security/Alphanumeric Captcha” and in “Allowed Validations” field select validation which you have created just now.
  •      Now go to Sitecore Form Editor and you will see Alphanumeric Captcha control inside Security tab

Alphanumeric Captcha



  •        Drag and drop control into your form
  •      Do not forget to check “AlphaNumericCaptcha Validator” checkbox otherwise it will not work.

Alphanumeric Captcha


  •      Render form into your page and Enjoy Alphanumeric Captcha

   

Comments

Popular posts from this blog

Sitecore 10.2 - “Failed to start service ‘Sitecore Marketing Automation Engine’” on Windows 11

Sitecore 10.2 - “Failed to start service ‘Sitecore Marketing Automation Engine' ” on Windows 11 Today I started to install Sitecore 10.2 using Sitecore Instance Manager on Windows 11 and I got this issue “Failed to start service ‘Sitecore Marketing Automation Engine' ” . Error : On event viewer it was showing the below error: I also tried to run ‘ Sitecore.MAEngine.exe ’ like this C:\Windows\system32>C:\inetpub\wwwroot\sclocal102xconnect.dev.local\App_Data\jobs\continuous\AutomationEngine\Sitecore.MAEngine.exe Which was throwing below error: Starting Marketing Automation Engine... 2022-01-29 22:21:11 ERR Error initializing XConnect client. System.AggregateException: One or more errors occurred. ---> Sitecore.XConnect.XdbCollectionUnavailableException: An error occurred while sending the request. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected err...

Sitecore Custom API Issue with Federation Authentication

Sitecore Custom API Issue with Federation Authentication In earlier segments, detailed in Part 1 and Part 2 of the blogs on Keycloak Integration with Sitecore, I introduced Keycloak functionality for CM login. Concurrently, I addressed a necessity to develop custom APIs for retrieving Sitecore users and roles. Following the development of custom APIs, during authentication failures, the API erroneously returned a status code of 200 instead of 401. The problem arose because API requests were being routed through the "owin.identityProviders" pipeline, which was not intended for API usage. Solution: When OWIN identifies a 401 response and the AuthenticationMode is set to "Active," it fails to capture the URL hash included in the request. Another choice is to activate the "Passive" AuthenticationMode, wherein OWIN refrains from actively intercepting 401 responses. In passive mode, your application needs to explicitly issue a Challenge to trigger the OWIN aut...

Azure AD Integration with Sitecore 10.2

 Azure AD Integration with Sitecore 10.2 Sitecore identity server that comes with Sitecore 9.1 allows you to log in through an external identity provider like Azure Active Directory, Facebook, Apple, or Google. It is built on Federation Authentication. What is Federation Authentication? Federation authentication is a technology to allows users to access multiples application, tools, and domains using one credential. Using one set of credential user can access multiple applications, and resources after authentication.  Federation authentication consists of two systems, the Identity provider and the Service provider. Identity providers that maintain/create/manage identity information like name, email address, device, and location. Some examples of identity providers are Azure AD, Google, Facebook, and Apple. Service providers basically refer to a website, software, or app that the user is trying to access and SP basically relies on the identity provider to authenticate the user ...