# Sample: Create a custom CAPTCHA forms widget

## Overview

The following article describes how to create a custom CAPTCHA widget using Google reCAPTCHA v2 or v3. This is a forms widget and you can place it in a form.\
For more information, see [Create and design forms](https://www.progress.com/documentation/sitefinity-cms/create-and-design-forms).

> info **PREREQUISITES**: Before using Google reCAPTCHA, you must:
>
> * Register your site get an API key pair at [Google reCAPTCHA](http://www.google.com/recaptcha/admin).\
>   You can generate an API key for either reCAPTCHA v2 or reCAPTCHA v3 and then use it with the corresponding widget from this tutorial.
> * You must update your privacy and GDPR statements according to Google reCAPTCHA policies.

## Configure Sitefinity CMS

Before implementing the widget, you must configure Sitefinity CMS.\
Perform the following:

1. In Sitefinity backend, navigate to *Administration* » *Settings* » *Advanced*.
2. In the treeview, expand *WebSecurity* » *Captcha* and click *Parameters*.
3. Create the following parameters:
   * *Key* `VerificationUrl` and *Value* `https://www.google.com/recaptcha/api/siteverify`
   * *Key* `ResponseKey` and *Value* `g-recaptcha-response`
   * *Key* `SecretKey` and *Value* `<The secret from the API key pair that you have created>`

     > info  **NOTE**: The version of the reCAPTCHA configuration for the secret key must correspond to the version of the reCAPTCHA widget that you are creating.
4. Save your changes.

## Create the ViewComponent

You create the widget’s `ViewComponent` in the Renderer application.\
Perform the following:

1. Open the ASP.NET Core Renderer in Visual Studio.
2. In the context menu of the Renderer project, click *Add* » *New Folder*.
3. Name the folder `ViewComponents`
4. Inside the folder, add a class and name it `Captcha2ViewComponent.cs` or `Captcha3ViewComponent.cs`, depending on the version of the Google reCAPTCHA you want to create.
5. In the class paste one of the following codes:

**reCAPTCHA v2**

```C#
using System;
using Microsoft.AspNetCore.Mvc;
using Progress.Sitefinity.AspNetCore.ViewComponents;
using Progress.Sitefinity.Renderer.Forms;

namespace SandboxWebApp.ViewComponents
{
   /// <summary>
   /// Captcha-V2 view component.
   /// </summary>
   [SitefinityFormWidget(FormFieldType.Captcha, Title = "CAPTCHA 2", Order = 1, Section = WidgetSection.Other)]
   public class Captcha2ViewComponent : ViewComponent
   {
       /// <summary>
       /// Invokes the view.
       /// </summary>
       /// <param name="context">Context.</param>
       /// <returns>View component.</returns>
       public IViewComponentResult Invoke(IViewComponentContext context)
       {
           if (context == null)
           {
               throw new ArgumentNullException(nameof(context));
           }

           context.SetHideEmptyVisual(true);

           return this.View();
       }
   }
}
```

**reCAPTCHA v3**

```C#
using System;
using Microsoft.AspNetCore.Mvc;
using Progress.Sitefinity.AspNetCore.ViewComponents;
using Progress.Sitefinity.Renderer.Forms;

namespace SandboxWebApp.ViewComponents
{
   /// <summary>
   /// Captcha-V3 view component.
   /// </summary>
   [SitefinityFormWidget(FormFieldType.Captcha, Title = "CAPTCHA 3", Order = 1, Section = WidgetSection.Other)]
   public class Captcha3ViewComponent : ViewComponent
   {
       /// <summary>
       /// Invokes the view.
       /// </summary>
       /// <param name="context">Context.</param>
       /// <returns>View component.</returns>
       public IViewComponentResult Invoke(IViewComponentContext context)
       {
           if (context == null)
           {
               throw new ArgumentNullException(nameof(context));
           }

           context.SetHideEmptyVisual(true);

           return this.View();
       }
   }
}
```

## Create the View

You create the widget’s `View` in the Renderer application.\
Perform the following:

1. In the context menu of the Renderer project, click *Add* » *New Folder* and create one of the following folder structures, depending on the version of the Google reCAPTCHA that you want to create:
   * `Views/Shared/Components/Captcha2`
   * `Views/Shared/Components/Captcha3`
2. Inside the `Captcha2` or `Captcha3` folder, add a code file and name it `Default.cshtml`
3. In the file paste one of the following codes:

**reCAPTCHA v2**

```Razor
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Progress.Sitefinity.AspNetCore

@using Progress.Sitefinity.AspNetCore.ViewComponents;
@using Progress.Sitefinity.AspNetCore.Web
@inject IRenderContext renderContext;

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
       section-name="Bottom"
       async defer></script>
<script src="scripts/captcha2.js" section-name="Top"></script>

<div>
   <div id="captchav2" class="@("mb-3 " + (renderContext.IsEdit ? "pe-none" : ""))"></div>
</div>
```

**reCAPTCHA v3**

```Razor
@addTagHelper *, Progress.Sitefinity.AspNetCore

@using Progress.Sitefinity.AspNetCore.ViewComponents;

<script src="https://www.google.com/recaptcha/api.js" section-name="Bottom"></script>
<script src="scripts/captcha3.js" section-name="Top"></script>

<div data-sf-role="captcha"></div>
```

## Create the Script

You create the widget’s script in the Renderer application.\
Perform the following:

1. In the context menu of the Renderer project, click *Add* » *New Folder*.
2. Create a folder and name it `Scripts`
3. Inside the `Scripts` folder, add a code file and name it `captcha2.js` or `captcha3.js`, depending on the version of the Google reCAPTCHA that you want to create.
4. In the file paste one of the following codes:

**reCAPTCHA v2**

```JavaScript
(function () {    
   window.onloadCallback = renderCaptcha;

   document.addEventListener('widgetLoaded', function (args) {        
       if (args.detail.model.Name === "Captcha2") {
           renderCaptcha();
       }
   });

   function renderCaptcha() {
       grecaptcha.render('captchav2', {
           'sitekey': <Captcha V2 site key>
       });
   }
})();
```

**reCAPTCHA v3**

```JavaScript
(function () {
   function init() {
       var captchaForms = [];
       var formContainers = document.querySelectorAll('[data-sf-role="form-container"]');

       formContainers.forEach(container => {
           var hasCaptcha = container.parentNode.querySelector('[data-sf-role="captcha"]');
           if (hasCaptcha) {
               captchaForms.push(container.parentNode);
           }
       });

       captchaForms.forEach((form, i) => {
           var submitButton = form.querySelector('[data-sf-role="submit-button-container"] button');
           if (submitButton) {
               var submitId = 'onCaptchaSubmit' + i;
               window[submitId] = function () {
                   form.dispatchEvent(new Event('submit'));
               };
               submitButton.classList.add('g-recaptcha');
               submitButton.setAttribute('data-sitekey', <Captcha V3 site key>);
               submitButton.setAttribute('data-callback', submitId);
           }
       });
   }
   document.addEventListener('DOMContentLoaded', init);
})();
```

> info **NOTE**: In the code samples above, change the `<Captcha V2 site key>` or `<Captcha V3 site key>` with the actual site key from the configured API key pair.

> success **RESULT**: After you build the project, the widget is displayed inside the forms widget selector when you are editing or creating ASP.NET Core forms.

## Run the sample

This sample is available in Sitefinity’s GitHub repository. You can run and play with it.\
To do this, perform the following:

1. Go to Sitefinity’s GitHub repository [Sitefinity ASP.NET Core samples](https://github.com/Sitefinity/sitefinity-aspnetcore-mvc-samples).
2. Expand *Code* and click *Download ZIP*.
3. Extract the files on your computer.
4. In the extracted folder, navigate to `sitefinity-aspnetcore-mvc-samples-master/src/captcha` folder.
5. Open the `captcha.sln` in Visual Studio.
6. Open the `appsettings.json` file.
7. In section `Sitefinity`, change the `Url` property to the URL of your Sitefinity CMS site.\
   If you have deployed Sitefinity CMS on the IIS, point to `https://localhost:<https_port>`.
8. In Visual Studio, in the context menu of `captcha` project, click *View in Browser*.
9. Log in to your Sitefinity CMS instance and place the widget on a page.
