React Captcha Component: A step-by-step Integration Guide

Unlike Recaptcha the Stalker -- BotDetect CAPTCHA works in China! Licensable source-code; self-hosted -- doesn't stalk -- nor does it slurp your form-data! Think: GDPR & LGPD!

Click on the link below that matches your BotDetect CAPTCHA React Component usage scenario:

..............................................................

React-based Frontend and the web API with MVC Core 1/2 on Backend

Step-1) Installation

To protect an application that has a React-based frontend and the web API with ASP.NET Core MVC on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect ASP.NET CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend

Reference BotDetect ASP.NET CAPTCHA Component

The free version nuget is available on nuget.org -- while the enterprise version nuget is available in the nuget folder of the enterprise version installation and archive.

Run the following command in the Package Manager Console:

PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/net 
             https://captcha.com/schema/net/botdetect-4.4.2.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint.ashx Path

Add the BotDetect section into your /your-app-backend-folder/appsettings.json file:

{
  "BotDetect" : {
     "CaptchaEndpointPath" : "simple-captcha-endpoint.ashx"
  }
}

Add the highlighted lines into your app's Startup class (Startup.cs):

public class Startup
{
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
    ...

    // configure your application pipeline to use SimpleCaptcha middleware
    app.UseSimpleCaptcha(Configuration.GetSection("BotDetect"));

    ...
  }

  // This method gets called by the runtime. Use this method to add services to the container.
  public void ConfigureServices(IServiceCollection services)
  {
    // Comment the next line if your app is running on the .NET Core 2.0
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddMemoryCache(); // Adds a default in-memory 
                                       // implementation of 
                                       // IDistributedCache

    // Add framework services.
    services.AddMvc();
  }
}

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- web API with MVC Core Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The corrensponding properties must be added to YourFormModel:

public class YourFormModel
{
  public string CaptchaId { get; set; }
  public string UserEnteredCaptchaCode { get; set; }
}

The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here is the C# code snippet:

// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

using BotDetect.Web;
using Microsoft.AspNetCore.Mvc;

namespace App.Controllers
{
  [Route("your-app-backend-path")]
  public class YourFormController : Controller
  {
    [HttpPost]
    public IActionResult Post([FromBody] Models.YourFormModel value)
    {
      string userEnteredCaptchaCode = value.UserEnteredCaptchaCode;
      string captchaId = value.CaptchaId;

      // create a captcha instance to be used for the captcha validation
      SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha();
      // execute the captcha validation
      bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId);

      if (isHuman == false)
      {
        // captcha validation failed; notify the frontend 
        // TODO: consider logging the attempt
        return Content("{\"success\":false}", "application/json; charset=utf-8");
      }
      else
      {
        // TODO: captcha validation succeeded; execute the protected action
        // TODO: do not forget to notify the frontend about the results
      }
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and the legacy ASP.NET MVC on Backend

Step-1) Installation

To protect an application that has a React-based frontend and the legacy ASP.NET MVC (MVC1-5) on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect ASP.NET CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend

Reference BotDetect ASP.NET CAPTCHA Component

The free version nuget is available on nuget.org -- while the enterprise version nuget is available in the nuget folder of the enterprise version installation and archive.

Run the following command in the Package Manager Console:

PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/net 
             https://captcha.com/schema/net/botdetect-4.4.2.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint.ashx path

Register the simple-captcha-endpoint.ashx path, and map it to the SimpleCaptchaHandler, by adding the highlighted lines from the snippet below into your app's web.config file.

<system.web>
  <httpHandlers>
    <!-- register the HttpHandler that serves BotDetect Simple API requests -->
    <add verb="GET" path="simple-captcha-endpoint.ashx"
         type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </httpHandlers>
</system.web>
<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <handlers>
    <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) -->
    <remove name="BotDetectCaptchaHandler"/>
    <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
         verb="GET" path="simple-captcha-endpoint.ashx"
         type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </handlers>
</system.webServer>

Configure your app's router to do not process simple-captcha-endpoint.ashx requests by adding the following line into your App_Start\RouteConfig.cs file:

public class RouteConfig 
{ 
  public static void RegisterRoutes(RouteCollection routes) 
  { 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    // BotDetect requests must not be routed 
    routes.IgnoreRoute("{*botdetect}", 
    new { botdetect = @"(.*)simple-captcha-endpoint\.ashx" });

    routes.MapRoute( 
        name: "Default", 
        url: "{controller}/{action}/{id}", 
        defaults: new { controller = "Example", action = "Index", 
        id =UrlParameter.Optional } 
    ); 
  } 
}

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- legacy ASP.NET MVC 1-5 Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The corrensponding properties must be added to YourFormModel:

public class YourFormModel
{
  public string CaptchaId { get; set; }
  public string UserEnteredCaptchaCode { get; set; }
}

The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here are the C# and VB.NET code snippets:

// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

[...]
using BotDetect.Web;

namespace App.Controllers
{
  public class YourFormController : Controller
  {
    [HttpPost]
    public ContentResult PostAction(YourFormModel yourFormModel)
    {
      string userEnteredCaptchaCode = yourFormModel.UserEnteredCaptchaCode;
      string captchaId = yourFormModel.CaptchaId;

      // create a captcha instance to be used for the captcha validation
      SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha();
      // execute the captcha validation
      bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId);

      if (isHuman == false) 
      {
        // captcha validation failed; notify the frontend 
        // TODO: consider logging the attempt		
        return Content("{\"success\":false}", "application/json; charset=utf-8");
      }
      else
      {
        // TODO: captcha validation succeeded; execute the protected action
        // TODO: do not forget to notify the frontend about the results
      }    
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and the legacy ASP.NET Web-API 2 on Backend

Step-1) Installation

To protect an application that has a React-based frontend and the legacy ASP.NET Web-API 2 on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect ASP.NET CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend

Reference BotDetect ASP.NET CAPTCHA Component

The free version nuget is available on nuget.org -- while the enterprise version nuget is available in the nuget folder of the enterprise version installation and archive.

Run the following command in the Package Manager Console:

PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/net 
             https://captcha.com/schema/net/botdetect-4.4.2.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint.ashx path

Register the simple-captcha-endpoint.ashx path, and map it to the SimpleCaptchaHandler, by adding the highlighted lines from the snippet below into your app's web.config file.

<system.web>
  <httpHandlers>
    <!-- register the HttpHandler that serves BotDetect Simple API requests -->
    <add verb="GET" path="simple-captcha-endpoint.ashx"
         type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </httpHandlers>
</system.web>
<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <handlers>
    <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) -->
    <remove name="BotDetectCaptchaHandler"/>
    <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
         verb="GET" path="simple-captcha-endpoint.ashx"
         type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </handlers>
</system.webServer>

Configure your app's router to do not process simple-captcha-endpoint.ashx requests by adding the following line into your App_Start\WebApiConfig.cs file:

config.Routes.IgnoreRoute("botdetect", @"(.*)simple-captcha-endpoint\.ashx");

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- legacy ASP.NET WebAPI2 Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The corrensponding properties must be added to YourFormModel:

public class YourFormModel
{
  public string CaptchaId { get; set; }
  public string UserEnteredCaptchaCode { get; set; }
}

The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here are the C# and VB.NET code snippets:

// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Newtonsoft.Json;
using BotDetect.Web;

namespace App.Controllers
{
  public class YourFormController : ApiController
  {
    public HttpResponseMessage Post([FromBody]Models.YourFormModel value)
    {
      string userEnteredCaptchaCode = value.UserEnteredCaptchaCode;
      string captchaId = value.CaptchaId;
		
      // create a captcha instance to be used for the captcha validation
      SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha();
      // execute the captcha validation
      bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId);

      if (isHuman == false) 
      {
        // captcha validation failed; notify the frontend 
        // TODO: consider logging the attempt
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent("{\"success\":false}", Encoding.UTF8, "application/json");
        return response;
      }
      else
      {
        // TODO: captcha validation succeeded; execute the protected action
        // TODO: do not forget to notify the frontend about the results
      }    
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and the legacy ASP.NET Generic Handler on Backend

Step-1) Installation

To protect an application that has a React-based frontend and the legacy ASP.NET Generic Handler on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect ASP.NET CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend

Reference BotDetect ASP.NET CAPTCHA Component

The free version nuget is available on nuget.org -- while the enterprise version nuget is available in the nuget folder of the enterprise version installation and archive.

Run the following command in the Package Manager Console:

PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/net"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/net 
             https://captcha.com/schema/net/botdetect-4.4.2.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint.ashx path

Register the simple-captcha-endpoint.ashx path, and map it to the SimpleCaptchaHandler, by adding the highlighted lines from the snippet below into your app's web.config file.

<system.web>
  <httpHandlers>
    <!-- register the HttpHandler that serves BotDetect Simple API requests -->
    <add verb="GET" path="simple-captcha-endpoint.ashx"
         type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </httpHandlers>
</system.web>
<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <handlers>
    <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) -->
    <remove name="BotDetectCaptchaHandler"/>
    <add name="BotDetectCaptchaHandler" preCondition="integratedMode" 
         verb="GET" path="simple-captcha-endpoint.ashx"
         type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/>
  </handlers>
</system.webServer>

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- legacy ASP.NET Generic Handler Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here are the C# and VB.NET code snippets:

<%@ WebHandler Language="C#" Class="yourFormPostHandler" %>
// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

using System;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BotDetect.Web;

public class YourFormPostHandler : IHttpHandler
{
  public void ProcessRequest (HttpContext context)
  {
    if (HttpContext.Current.Request.HttpMethod == "POST")
    {
      string dataJson = new StreamReader(context.Request.InputStream).ReadToEnd();

      Dictionary<string, string> formDataObj = new Dictionary<string, string>();
      formDataObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataJson);

      string userEnteredCaptchaCode = formDataObj["userEnteredCaptchaCode"];
      string captchaId = formDataObj["captchaId"];

      // create a captcha instance to be used for the captcha validation
      SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha();
      // execute the captcha validation
      bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId);

      if (isHuman == false) 
      {
        // captcha validation failed; notify the frontend 
        // TODO: consider logging the attempt
        context.Response.ContentType = "application/json; charset=utf-8";
        context.Response.Write("{\"success\":false}");
        return;
      }
      else
      {
        // TODO: captcha validation succeeded; execute the protected action
        // TODO: do not forget to notify the frontend about the results
      }    
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and Java Servlet on Backend

Step-1) Installation:

To protect an application that has a React-based frontend and Servlet on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect Java CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend

Install BotDetect Java CAPTCHA dependencies

The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.

To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines to your app's backend pom.xml file:

<repository>
  <id>captcha</id>
  <name>BotDetect Captcha Repository</name>
  <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url>
</repository>

Then, declare the BotDetect dependency in your app's backend pom.xml file, too:

<dependency>
  <groupId>com.captcha</groupId>
  <artifactId>botdetect-servlet</artifactId>
  <version>4.0.beta3.7</version>
</dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/WEB-INF/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/java"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/java 
             https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint path

Update your application configuration:

Register the simple-captcha-endpoint path, and map it to the SimpleCaptchaServlet, by adding the highlighted lines from the snippet below into your app's web.xml file.

<servlet>
  <servlet-name>BotDetect Captcha</servlet-name>
  <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>BotDetect Captcha</servlet-name>
  <url-pattern>/simple-captcha-endpoint</url-pattern>
</servlet-mapping>

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- Servlet Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here is the Java code snippet:

// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

[...]

import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class YourFormPostServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
   
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());

    String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString();
    String captchaId = formDataObj.get("captchaId").getAsString();

    // create a captcha instance to be used for the captcha validation
    SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request);
    // execute the captcha validation
    boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId);

    if (isHuman == false) {
      // captcha validation failed; notify the frontend 
      // TODO: consider logging the attempt
      response.setContentType("application/json; charset=utf-8");
      response.getWriter().write("{\"success\":false}");
    } else {
      // TODO: captcha validation succeeded; execute the protected action
      // TODO: do not forget to notify the frontend about the results
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and Java Spring on Backend

Step-1) Installation:

To protect an application that has a React-based frontend and Spring on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect Java CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend

Install BotDetect Java CAPTCHA dependencies

The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.

To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines to your app's backend pom.xml file:

<repository>
  <id>captcha</id>
  <name>BotDetect Captcha Repository</name>
  <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url>
</repository>

Then, declare the BotDetect dependency in your app's backend pom.xml file, too:

<dependency>
  <groupId>com.captcha</groupId>
  <artifactId>botdetect-servlet</artifactId>
  <version>4.0.beta3.7</version>
</dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/WEB-INF/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/java"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/java 
             https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint path

Update your application configuration:

Register the simple-captcha-endpoint path, and map it to the SimpleCaptchaServlet, by adding the highlighted lines from the snippet below into your app's web.xml file.

<servlet>
  <servlet-name>BotDetect Captcha</servlet-name>
  <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>BotDetect Captcha</servlet-name>
  <url-pattern>/simple-captcha-endpoint</url-pattern>
</servlet-mapping>

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- Spring Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here is the Java code snippet:

// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

[...]
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

@Controller
public class YourFormPostController {
    
  @RequestMapping(value = "your-app-backend-path", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
  @ResponseBody
  public String yourFormPostAction(HttpServletRequest request) throws IOException {

    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());

    String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString();
    String captchaId = formDataObj.get("captchaId").getAsString();

    // create a captcha instance to be used for the captcha validation
    SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request);
    // execute the captcha validation
    boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId);

    if (isHuman == false) {
      // captcha validation failed; notify the frontend 
      // TODO: consider logging the attempt
      return "{\"success\":false}";
    } else {
      // TODO: captcha validation succeeded; execute the protected action
      // TODO: do not forget to notify the frontend about the results
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and Java Struts on Backend

Step-1) Installation:

To protect an application that has a React-based frontend and Struts on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect Java CAPTCHA library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend

Install BotDetect Java CAPTCHA dependencies

The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.

To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines to your app's backend pom.xml file:

<repository>
  <id>captcha</id>
  <name>BotDetect Captcha Repository</name>
  <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url>
</repository>

Then, declare the BotDetect dependency in your app's backend pom.xml file, too:

<dependency>
  <groupId>com.captcha</groupId>
  <artifactId>botdetect-servlet</artifactId>
  <version>4.0.beta3.7</version>
</dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed

By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Create the /your-app-backend-folder/WEB-INF/botdetect.xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/java"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/java 
             https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Register the simple-captcha-endpoint path

Update your application configuration:

Register the simple-captcha-endpoint path, and map it to the SimpleCaptchaServlet, by adding the highlighted lines from the snippet below into your app's web.xml file.

<servlet>
  <servlet-name>BotDetect Captcha</servlet-name>
  <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>BotDetect Captcha</servlet-name>
  <url-pattern>/simple-captcha-endpoint</url-pattern>
</servlet-mapping>

Configure your app's router to do not process simple-captcha-endpoint requests by adding the following line into your struts.xml configuration file:

<constant name="struts.action.excludePattern" value="/simple-captcha-endpoint"/>

Step-2.3) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.4) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- Struts Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here is the Java code snippet:

// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

[...]
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class YourFormPostAction extends ActionSupport {
    
  public String execute() throws IOException {
    HttpServletRequest request = ServletActionContext.getRequest();
    
    if (!request.getMethod().equals("POST")) {
      return Action.ERROR;
    }
    
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());

    String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString();
    String captchaId = formDataObj.get("captchaId").getAsString();

    // create a captcha instance to be used for the captcha validation
    SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request);
    // execute the captcha validation
    boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId);

    if (isHuman == false) {
      // captcha validation failed; notify the frontend 
      // TODO: consider logging the attempt
      HttpServletResponse response = ServletActionContext.getResponse();
      response.setContentType("application/json; charset=utf-8");
      response.getWriter().write("{\"success\":false}");
    } else {
      // TODO: captcha validation succeeded; execute the protected action
      // TODO: do not forget to notify the frontend about the results
    }
  }
}

Step-4) Configuring the Other Captcha Options

All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

..............................................................

React-based Frontend and the plain PHP on Backend

Step-1) Installation

To protect an application that has a React-based frontend and the plain PHP on backend the following have to be installed:

  • App's frontend: BotDetect CAPTCHA React Component
  • App's backend: BotDetect PHP CAPTCHA Library

Step-1.1) Install BotDetect CAPTCHA React Component in Your App's Frontend

Install the BotDetect CAPTCHA React Component

npm install reactjs-captcha --save

Step-1.2) Install BotDetect PHP CAPTCHA Library in Your App's Backend

Install BotDetect PHP CAPTCHA Library

Download the BotDetect PHP CAPTCHA library. The downloaded zip file contains the botdetect-captcha-lib folder with BotDetect PHP CAPTCHA library. Copy it into the root folder of the app's backend. The final backend folder structure should look in the following way: /your-app-backend-folder/botdetect-captcha-lib/

Reconfigure BotDetect CAPTCHA PHP Library's Server-side Persistence Mechanism, If Needed

By default, BotDetect PHP CAPTCHA uses SQLite3 as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.

Please Note

If you use Windows for development you will have to enable the SQLite3 PHP extension (php_sqlite3.dll) in php.ini. Unlike elsewhere, it is not enabled by default on Windows.

On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite3 -- if, per instance, your load-balanced application requires them.

Step-2) Displaying Captcha in a Form

To display a captcha in a form the following has to be done:

  • Captcha style has to be defined.
  • React Captcha Component on frontend has to be connected with the BotDetect PHP CAPTCHA library on backend.

Step-2.1) Define Your First Captcha Style

The most basic valid captcha style has to have the following two properties defined:

  • name -- the name of a captcha style, and
  • userInputID -- the ID of an <input> element in which users will enter captcha codes

Add them to the botdetect.xml that can be found at:
/your-app-backend-folder/botdetect-captcha-lib/config/botdetect.xml

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/php"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://captcha.com/schema/php 
             https://captcha.com/schema/php/botdetect-4.2.5.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>yourFirstCaptchaStyle</name>
      <userInputID>yourFirstCaptchaUserInput</userInputID>
    </captchaStyle>
  </captchaStyles>
</botdetect>

Step-2.2) Place Captcha in Your Form

To the render() method of your View; defined within yourFormWithCaptcha.jsx file -- at the exact place where you want to be displaying captcha challenges -- add the following lines:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  […]

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="yourFirstCaptchaUserInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
  
  […]
}

export default YourFormWithCaptcha;

Note that the values of both the captchaStyleName and input id attributes have to match the corresponding name and userInputID settings of a particular captcha style defined in the botdetect.xml file.

Step-2.3) Set the captchaEndpoint in Your App's Frontend

Set the captchaEndpoint property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into yourFormWithCaptcha.jsx file:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint: 
        'https://your-app-backend-hostname.your-domain.com/botdetect-captcha-lib/simple-botdetect.php'
    });
  }
  
  […]
}

export default YourFormWithCaptcha;

That is it. Open your form now. It should have a captcha rendered on it.

Please Note

Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.

Step-3) Captcha Validation

To validate a captcha actions are needed on both the frontend and backend side.

Step-3.1) Captcha Validation -- React Frontend Code

A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.

When that particular post request completes:

  • If the captcha validation failed -- the .captcha.reloadImage() needs to be called in order to generate a new captcha challenge.
  • If the captcha validation succeeded -- you proceed with your application workflow.

Here is an example of the React code with such a post and captcha validation result processing on the frontend side:

import React from 'react';
import axios from 'axios';
import { Captcha, captchaSettings } from 'reactjs-captcha';

class YourFormWithCaptcha extends React.Component {

  constructor(props) {
    super(props);

    captchaSettings.set({
      captchaEndpoint:
        'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'
    });
  }

  // process the yourFormWithCaptcha on submit event
  yourFormWithCaptchaOnSubmitHandler(event) {

    // the user-entered captcha code value to be validated at the backend side
    let userEnteredCaptchaCode = this.captcha.getUserEnteredCaptchaCode();

    // the id of a captcha instance that the user tried to solve
    let captchaId = this.captcha.getCaptchaId();

    let postData = {
      userEnteredCaptchaCode: userEnteredCaptchaCode,
      captchaId: captchaId
    };

    let self = this;

    // post the captcha data to the /your-app-backend-path on your backend.
    // make sure you import the axios in this view with: import axios from 'axios';
    axios.post(
        'https://your-app-backend-hostname.your-domain.com/your-app-backend-path',
        postData, {headers: {'Content-Type': 'application/json; charset=utf-8'}})
        .then(response => {
          if (response.data.success == false) {
            // captcha validation failed; reload image
            self.captcha.reloadImage();
            // TODO: maybe display an error message, too
          } else {
            // TODO: captcha validation succeeded; proceed with your workflow
          }
        });

    event.preventDefault();
  }

  render() {
    return (
      <section id="main-content">
        <form id="yourFormWithCaptchaForm" method="POST"
           onSubmit={this.yourFormWithCaptchaOnSubmitHandler.bind(this)}>

          {/* captcha challenge: placeholder */}
          <Captcha captchaStyleName="yourFirstCaptchaStyle"
                   ref={(captcha) => {this.captcha = captcha}} />
          <label>
            <span>Retype the characters from the picture:</span>
            {/* captcha code: user-input textbox */}
            <input id="userCaptchaInput" type="text"/>
          </label>

          <button type="submit" id="submitButton">Validate</button>
        </form>
      </section>
    )
  }
}

export default YourFormWithCaptcha;

Step-3.2) Captcha Validation -- the plain PHP Backend Code

The userEnteredCaptchaCode and captchaId values posted from the frontend are used to validate a captcha challenge on the backend.

The validation is performed by calling the:
Validate($userEnteredCaptchaCode, $captchaId).

In this example, the result of validation is sent back to the frontend as a json.

Here is the PHP code snippet:

<?php header('Content-Type: application/json; charset=utf-8');
// route:
// https://your-app-backend-hostname.your-domain.com/your-app-backend-path

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  require('botdetect-captcha-lib/simple-botdetect.php');

  $postedData = (array) json_decode(file_get_contents('php://input'), true);

  $userEnteredCaptchaCode = $postedData['userEnteredCaptchaCode'];
  $captchaId = $postedData['captchaId'];

  // create a captcha instance to be used for the captcha validation
  $yourFirstCaptcha = new SimpleCaptcha();
  // execute the captcha validation
  $isHuman = $yourFirstCaptcha->Validate($userEnteredCaptchaCode, $captchaId);

  if ($isHuman == false) {
    // captcha validation failed; notify the frontend 
    // TODO: consider logging the attempt
    echo "{\"success\":false}";
  } else {
    // TODO: captcha validation succeeded; execute the protected action
    // TODO: do not forget to notify the frontend about the results
  }
}

Step-4) Configuring the Other PHP Captcha Options

All BotDetect PHP CAPTCHA Simple API configuration options are set in the botdetect.xml file -- while their descriptions are in the Simple API configuration options page.

Please Note

The new experimental Simple API is still work-in-progress. This Integration Guide & Examples require you to have the React Captcha Component v1.3.1 on frontend, and one of the following BotDetect CAPTCHA releases on backend: ASP.NET v4.4.2+, Java v4.0.Beta3.7+, PHP v4.2.5+.

Current BotDetect Versions