How To Add BotDetect CAPTCHA Protection to Angular Application

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!

CAPTCHA Integration Steps

Integration in Angular application -- Introduction

BotDetect Captcha protection can be added to your Angular applications using the BotDetect CAPTCHA Angular Module. Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

and using validateUnsafe(callback) method to validate Captcha code on form submit:

export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  /**
   * On form submit.
   */
  validate(value, valid): void {

    this.captchaComponent.validateUnsafe((isCaptchaCodeCorrect: boolean) => {
      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }
    });
  }

}

PLEASE NOTE: Since Captcha protects some server-side action, a Captcha code needs to be validated again on the server-side -- in your backend tech specific way -- before that protected action is executed.

You can see how BotDetect Captcha protection is added to a simple Angular form by running the BotDetect Captcha integration code examples coming with the each BotDetect product's free download package.

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

Integration in Angular 2/4/5/6/7+ application

Angular 2/4/5/6/7+ app with ASP.NET backend

Install BotDetect CAPTCHA Angular Module

Step 1: Install BotDetect Captcha Angular Module

  • Angular 4/5/6/7+:

  • Angular 2.x:

Step 2: Load BotDetect Captcha Angular Module

If you use SystemJS, you will need to declare as bellow in your SystemJS config file:

System.config({
  paths: {
    // paths serve as alias
    'npm:': 'node_modules/'
  },
  map: {
    ...
    'angular-captcha': 'npm:angular-captcha'
  },
  packages: {
    ...
    'angular-captcha': {
      defaultExtension: 'js',
      main: 'index'
    },
  }
});

Step 3: Declare BotDetect Captcha Angular Module in your application

The following step ensures that BotDetect CAPTCHA library works properly in your Angular application. Please follow it carefully.

...
import { BotDetectCaptchaModule } from 'angular-captcha';

@NgModule({
  imports: [
    ...
    BotDetectCaptchaModule.forRoot({
      captchaEndpoint: 'captcha-endpoint/BotDetectCaptcha.ashx'
    })
  ],
  ...
})
export class AppModule { }

In the code above, we import BotDetectCaptchaModule, and then declare it in metadata imports of the NgModule. In case you want to add Captcha in a child module, you will need to use forChild instead of forRoot in the code above.

The BotDetectCaptchaModule requires you to configure BotDetect ASP.NET Captcha path to captchaEndpoint setting.

Before you set the path to captchaEndpoint setting, we need to clarify what we should set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect ASP.NET Captcha library. If you deployed BotDetect ASP.NET Captcha library in the root of your domain, then you don't need to set this path.
  • /BotDetectCaptcha.ashx: is HttpHandler path, which is described on Register BotDetect HttpHandler for CAPTCHA Requests guide below.

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/BotDetectCaptcha.ashx (replace the exact path of your domain). If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha who responded error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your Angular Template

Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

BotDetect Captcha Angular Module provides botdetect-captcha element to add Captcha in your forms. It has styleName attribute, which you can assign it a captcha style name defined in botdetect.xml configuration file.

Captcha Validation

Client-side Captcha validation in your Angular application

BotDetect Captcha Angular Module provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  /**
   * On form submit.
   */
  validate(value, valid): void {

    this.captchaComponent.validateUnsafe((isCaptchaCodeCorrect: boolean) => {
      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }
    });
  }

}

OR:

  • Using correctCaptcha directive attribute to validate Captcha code on blur event:
<input
  type="text"
  id="captchaCode"
  name="captchaCode"
  #captchaCode="ngModel"
  ngModel
  correctCaptcha
>

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

ASP.NET Server-side Captcha validation

...

import { CaptchaComponent } from 'angular-captcha';

@Component({
  ...
})
export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  constructor(private http: Http) { }

  /**
   * Validate captcha at server-side.
   */
  validate(value, valid): void {

    if (!valid) {
      return;
    }

    const exampleUrl = '/your-server-side-api-url';

    const postData = {
      captchaCode: this.captchaComponent.captchaCode,
      captchaId: this.captchaComponent.captchaId
    }

    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: headers });

    this.http.post(exampleUrl, data, options)
      .map((response: Response) => {

        if (response.json().success) {
          // CAPTCHA validation passed at server-side
        } else {
          // CAPTCHA validation falied at client-side
        }

        // reload Captcha image
        this.captchaComponent.reloadImage();
      })
      .catch((error:any) => Observable.throw(error.json().error));
  }

}

In the code above, we inject CaptchaComponent into ExampleComponent using @ViewChild. The CaptchaComponent exposes all Captcha workflow functions and vars that we will use during the form submission part of the workflow.

To validate Captcha at server-side, we need to send both captcha id (via captchaComponent.captchaId property) and captcha code visitor submited (via captchaComponent.captchaCode property) to server-side.

On request finish, we always reload Captcha by calling the reloadImage() function of CaptchaComponent. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in Web API 2:
using BotDetect.Web;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace ProductApp.Controllers
{
    public class ExampleController : ApiController
    {
        // POST api/example
        public HttpResponseMessage Post([FromBody]Models.BasicForm value)
        {
            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(value.CaptchaCode, value.CaptchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            string jsonString = JsonConvert.SerializeObject(validationResult);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            return response;
        }
    }
}
  • Server-side Captcha validation in a Generic Handler:
<%@ WebHandler Language="C#" Class="BasicHandler" %>
using System;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BotDetect.Web;

public class BasicHandler : 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 captchaId = formDataObj["captchaId"];
            string captchaCode = formDataObj["captchaCode"];

            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(captchaCode, captchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(validationResult));
        }
    }
}

Display Captcha error message in your Angular template

<div
  class="error"
  *ngIf="captchaCode.errors?.incorrectCaptcha && !captchaCode.pristine"
  >
  Incorrect captcha code.
</div>

Assuming you have used the correctCaptcha directive attribute in captcha code input field, to display captcha error message, simply check if incorrectCaptcha property exists in captchaCode.errors object. If it exists, this means that UI captcha validation failed.

ASP.NET server-side Configuration

Install BotDetect ASP.NET Captcha library on Server-side

Before integrating BotDetect Captcha in your Angular application, you need to ensure you have installed BotDetect ASP.NET Captcha library on your server where your Angular application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?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.0.xsd">

  <captchaStyles>
    
    <captchaStyle>
      <name>exampleCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>6</codeLength>
    </captchaStyle>

    <captchaStyle>
      <name>loginCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>4-6</codeLength>
      <codeStyle>Alphanumeric</codeStyle>
    </captchaStyle>

  </captchaStyles>

</botdetect>

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in root folder of your project. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

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

Angular 2/4/5/6/7+ app with JAVA backend

Install BotDetect CAPTCHA Angular Module

Step 1: Install BotDetect Captcha Angular Module

  • Angular 4/5/6/7+:

  • Angular 2.x:

Step 2: Load BotDetect Captcha Angular Module

If you use SystemJS, you will need to declare as bellow in your SystemJS config file:

System.config({
  paths: {
    // paths serve as alias
    'npm:': 'node_modules/'
  },
  map: {
    ...
    'angular-captcha': 'npm:angular-captcha'
  },
  packages: {
    ...
    'angular-captcha': {
      defaultExtension: 'js',
      main: 'index'
    },
  }
});

Step 3: Declare BotDetect Captcha Angular Module in your application

The following step ensures that BotDetect CAPTCHA library works properly in your Angular application. Please follow it carefully.

...
import { BotDetectCaptchaModule } from 'angular-captcha';

@NgModule({
  imports: [
    ...
    BotDetectCaptchaModule.forRoot({
      captchaEndpoint: 'captcha-endpoint/botdetectcaptcha'
    })
  ],
  ...
})
export class AppModule { }

In the code above, we import BotDetectCaptchaModule, and then declare it in metadata imports of the NgModule. In case you want to add Captcha in a child module, you will need to use forChild instead of forRoot in the code above.

The BotDetectCaptchaModule requires you to configure BotDetect Java Captcha path to captchaEndpoint setting.

Before you set the path to captchaEndpoint setting, we need to clarify what we should set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect Java Captcha library. If you deployed BotDetect Java Captcha library in the root of your domain, then you don't need to set this path.
  • /botdetectcaptcha: is SimpleCaptchaServlet path, which is described on Register SimpleCaptchaServlet guide below.

To ensure that you set the captchaEndpoint to right path, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/botdetectcaptcha (replace the 'yourdomain.com' with your domain). If opening the url in browser results with an error message ('unknown command') then you set the right path since it is the BotDetect Captcha that responded with 'unknown command' error. Otherwise, if you failed to set right path, then your server will respond with 404 instead.

Please note, in order to perform this check, BotDetect Captcha Generator needs to be deployed to your server (described in II. Captcha Generator server-side configuration).

Display BotDetect CAPTCHA In Your Angular Template

Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

BotDetect Captcha Angular Module provides botdetect-captcha element to add Captcha in your forms. It has styleName attribute, which you can assign it a captcha style name defined in botdetect.xml configuration file.

Captcha Validation

Client-side Captcha validation in your Angular application

BotDetect Captcha Angular Module provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  /**
   * On form submit.
   */
  validate(value, valid): void {

    this.captchaComponent.validateUnsafe((isCaptchaCodeCorrect: boolean) => {
      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }
    });
  }

}

OR:

  • Using correctCaptcha directive attribute to validate Captcha code on blur event:
<input
  type="text"
  id="captchaCode"
  name="captchaCode"
  #captchaCode="ngModel"
  ngModel
  correctCaptcha
>

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

JAVA Server-side Captcha validation

...

import { CaptchaComponent } from 'angular-captcha';

@Component({
  ...
})
export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  constructor(private http: Http) { }

  /**
   * Validate captcha at server-side.
   */
  validate(value, valid): void {

    if (!valid) {
      return;
    }

    const exampleUrl = '/your-server-side-api-url';

    const postData = {
      captchaCode: this.captchaComponent.captchaCode,
      captchaId: this.captchaComponent.captchaId
    }

    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: headers });

    this.http.post(exampleUrl, data, options)
      .map((response: Response) => {

        if (response.json().success) {
          // CAPTCHA validation passed at server-side
        } else {
          // CAPTCHA validation falied at client-side
        }

        // reload Captcha image
        this.captchaComponent.reloadImage();
      })
      .catch((error:any) => Observable.throw(error.json().error));
  }

}

In the code above, we inject CaptchaComponent into ExampleComponent using @ViewChild. The CaptchaComponent exposes all Captcha workflow functions and vars that we will use during the form submission part of the workflow.

To validate Captcha at server-side, we need to send both captcha id (via captchaComponent.captchaId property) and captcha code visitor submited (via captchaComponent.captchaCode property) to server-side.

On request finish, we always reload Captcha by calling the reloadImage() function of CaptchaComponent. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.


  • Server-side Captcha validation in a Servlet is performed in the following way:
....

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

public class ExampleServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
   
    PrintWriter out = response.getWriter();
    Gson gson = new Gson();
    
    response.setContentType("application/json; charset=utf-8");
    
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());
    
    String captchaId = formDataObj.get("captchaId").getAsString();
    String captchaCode = formDataObj.get("captchaCode").getAsString();
    
    // validate captcha
    SimpleCaptcha captcha = SimpleCaptcha.load(request);
    boolean isHuman = captcha.validate(captchaCode, captchaId);
    
    if (isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }
    
    // the object that stores validation result
    ExampleValidationResult validationResult = new ExampleValidationResult();
    validationResult.setSuccess(isHuman);
    
    try {
      // write the validation result as json string for sending it back to client
      out.write(gson.toJson(validationResult));
    } catch(Exception ex) {
      out.write(ex.getMessage());
    } finally {
      out.close();
    }
  }
}

  • Server-side Captcha validation in a Spring MVC Controller is performed in the following way:
...
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

@Controller
public class ExampleController {

  @RequestMapping(value = "basic-captcha", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
  @ResponseBody
  public String exampleCaptcha(HttpServletRequest request) {
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = null;
    boolean result = false;

    try {
      formDataObj = (JsonObject) parser.parse(request.getReader());
    } catch (IOException ex) { }

    if (formDataObj != null) {
      String captchaId = formDataObj.get("captchaId").getAsString();
      String captchaCode = formDataObj.get("captchaCode").getAsString();

      // validate captcha
      SimpleCaptcha captcha = SimpleCaptcha.load(request);
      boolean isHuman = captcha.validate(captchaCode, captchaId);
      
      result = isHuman;
    }

    return "{\"success\":" + result.toString() + "}";
  }
}

  • Server-side Captcha validation in a Struts Action is performed in the following way:
...
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class ExampleAction {

  private boolean success = false;

  public boolean isSuccess() {
    return success;
  }

  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    
    if (!request.getMethod().equalsIgnoreCase("post")) {
      return Action.ERROR;
    }

    Map<String, String> mapParams = request.getParameterMap();
    Set<String> setKeys = mapParams.keySet();
    Iterator<String> temp = setKeys.iterator();
    String data = temp.next();

    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(data);

    if (formDataObj != null) {
      String captchaId = formDataObj.get("captchaId").getAsString();
      String captchaCode = formDataObj.get("captchaCode").getAsString();

      // validate captcha
      SimpleCaptcha captcha = SimpleCaptcha.load(request);
      boolean isHuman = captcha.validate(captchaCode, captchaId);
      
      this.success = isHuman;
    }

    return Action.SUCCESS;
  }
}

Display Captcha error message in your Angular template

<div
  class="error"
  *ngIf="captchaCode.errors?.incorrectCaptcha && !captchaCode.pristine"
  >
  Incorrect captcha code.
</div>

Assuming you have used the correctCaptcha directive attribute in captcha code input field, to display captcha error message, simply check if incorrectCaptcha property exists in captchaCode.errors object. If it exists, this means that UI captcha validation failed.

JAVA server-side Configuration

Install BotDetect Java Captcha library on Server-side

Before integrating BotDetect Captcha in your Angular application, you need to ensure you have installed BotDetect Java Captcha library on your server where your Angular application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?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.5.xsd">

  <captchaStyles>
    
    <captchaStyle>
      <name>exampleCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>6</codeLength>
    </captchaStyle>

    <captchaStyle>
      <name>loginCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>4-6</codeLength>
      <codeStyle>ALPHANUMERIC</codeStyle>
    </captchaStyle>

  </captchaStyles>

</botdetect>

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in WEB-INF/ folder. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

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

Angular 2/4/5/6/7+ app with PHP backend

Install BotDetect CAPTCHA Angular Module

Step 1: Install BotDetect Captcha Angular Module

  • Angular 4/5/6/7+:

  • Angular 2.x:

Step 2: Load BotDetect Captcha Angular Module

If you use SystemJS, you will need to declare as bellow in your SystemJS config file:

System.config({
  paths: {
    // paths serve as alias
    'npm:': 'node_modules/'
  },
  map: {
    ...
    'angular-captcha': 'npm:angular-captcha'
  },
  packages: {
    ...
    'angular-captcha': {
      defaultExtension: 'js',
      main: 'index'
    },
  }
});

Step 3: Declare BotDetect Captcha Angular Module in your application

The following step ensures that BotDetect CAPTCHA library works properly in your Angular application. Please follow it carefully.

...
import { BotDetectCaptchaModule } from 'angular-captcha';

@NgModule({
  imports: [
    ...
    BotDetectCaptchaModule.forRoot({
      captchaEndpoint: 'captcha-endpoint/simple-botdectect.php'
    })
  ],
  ...
})
export class AppModule { }

In the code above, we import BotDetectCaptchaModule, and then declare it in metadata imports of the NgModule. In case you want to add Captcha in a child module, you will need to use forChild instead of forRoot in the code above.

The BotDetectCaptchaModule requires you to configure BotDetect Java Captcha path to captchaEndpoint setting.

Before you set the path to captchaEndpoint setting, we need to clarify what we should set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect PHP Captcha library. If you deployed BotDetect PHP Captcha library in the root of your domain, then you don't need to set this path.
  • /captcha-endpoint/simple-botdectect.php is the Handler URL of the PHP script processing Captcha challenge Http requests and this if you use the BotDetect Captcha library in a Plain PHP application.
    Use /simple-captcha-handler if you use the following:

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser:
http://yourdomain.com/captcha-endpoint/simple-botdetect.php (replace the exact path of your domain).
If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha that responded with error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your Angular Template

Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

BotDetect Captcha Angular Module provides botdetect-captcha element to add Captcha in your forms. It has styleName attribute, which you can assign it a captcha style name defined in botdetect.xml configuration file.

Captcha Validation

Client-side Captcha validation in your Angular application

BotDetect Captcha Angular Module provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  /**
   * On form submit.
   */
  validate(value, valid): void {

    this.captchaComponent.validateUnsafe((isCaptchaCodeCorrect: boolean) => {
      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }
    });
  }

}

OR:

  • Using correctCaptcha directive attribute to validate Captcha code on blur event:
<input
  type="text"
  id="captchaCode"
  name="captchaCode"
  #captchaCode="ngModel"
  ngModel
  correctCaptcha
>

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

PHP Server-side Captcha validation

...

import { CaptchaComponent } from 'angular-captcha';

@Component({
  ...
})
export class ExampleComponent {

  /**
   * BotDetect CAPTCHA component.
   */
  @ViewChild(CaptchaComponent) captchaComponent: CaptchaComponent;

  constructor(private http: Http) { }

  /**
   * Validate captcha at server-side.
   */
  validate(value, valid): void {

    if (!valid) {
      return;
    }

    const exampleUrl = '/your-server-side-api-url';

    const postData = {
      captchaCode: this.captchaComponent.captchaCode,
      captchaId: this.captchaComponent.captchaId
    }

    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: headers });

    this.http.post(exampleUrl, data, options)
      .map((response: Response) => {

        if (response.json().success) {
          // CAPTCHA validation passed at server-side
        } else {
          // CAPTCHA validation falied at client-side
        }

        // reload Captcha image
        this.captchaComponent.reloadImage();
      })
      .catch((error:any) => Observable.throw(error.json().error));
  }

}

In the code above, we inject CaptchaComponent into ExampleComponent using @ViewChild. The CaptchaComponent exposes all Captcha workflow functions and vars that we will use during the form submission part of the workflow.

To validate Captcha at server-side, we need to send both captcha id (via captchaComponent.captchaId property) and captcha code visitor submited (via captchaComponent.captchaCode property) to server-side.

On request finish, we always reload Captcha by calling the reloadImage() function of CaptchaComponent. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in Plain PHP:
<?php
require("captcha-endpoint/simple-botdetect.php");

// directly accessing this script is an error
if (!$_SERVER['REQUEST_METHOD'] == "POST") {
  header("HTTP/1.1 400 Bad Request");
  exit;
}

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$userInput = $input["captchaCode"];
$captchaId = $input["captchaId"];

// Captcha validation
$ExampleCaptcha = new SimpleCaptcha();
$isHuman = $ExampleCaptcha->Validate($userInput, $captchaId);

if ($isHuman) {
  // Captcha validation passed
  // TODO: do whatever you want here
}
$result = array('success' => $isHuman);
echo json_encode($result, true);
exit;
  • Server-side Captcha validation in Symfony:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ExampleController extends Controller
{
  /**
   * @Route("/api/example", methods={"POST"})
   */
  public function postExampleAction(Request $request)
  {
    $postData = json_decode($request->getContent());
    
    $captchaCode = $postData->captchaCode;
    $captchaId = $postData->captchaId;

    // validate captcha
    $captcha = $this->container->get('simple_captcha')->getInstance();
    $isHuman = $captcha->Validate($captchaCode, $captchaId);
    
    if ($isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }

    // write the validation result as json string for sending it back to client
    $response = array('success' => $isHuman);
    return $this->json($response);
  }
}
  • Server-side Captcha validation in Laravel:
<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ExampleController extends Controller
{
  public function postAction(Request $request)
  {
    $captchaCode = $request->input('captchaCode');
    $captchaId = $request->input('captchaId');
    
    // validate captcha
    $isHuman = simple_captcha_validate($captchaCode, $captchaId);

    if ($isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }
   
    // write the validation result as json string for sending it back to client
    $response = array('success' => $isHuman);
    return response()->json($response);
  }
}
  • Server-side Captcha validation in CakePHP:
<?php 

namespace App\Controller;

use Cake\Controller\Controller;

class ExampleController extends Controller
{
  public function initialize()
  {
    parent::initialize();

    // load the Simple Captcha component
    $this->loadComponent('CakeCaptcha.SimpleCaptcha');
  }

  public function postExampleAction()
  {
    $this->autoRender = false;
    
    if ($this->request->is('post')) {
      $captchaCode = $this->request->data['captchaCode'];
      $captchaId = $this->request->data['captchaId'];
      
      // validate captcha
      $isHuman = simple_captcha_validate($captchaCode, $captchaId);

      if ($isHuman) {
        // Captcha validation passed
        // TODO: do whatever you want here
      }

      // write the validation result as json string for sending it back to client
      $result = array('success' => $isHuman);
      return $this->response->withType('application/json')
              ->withStringBody(json_encode($result));
    }
  }
}
  • Server-side Captcha validation in CodeIgniter:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Example extends CI_Controller {

  public function postExampleAction()
  {
    // load the BotDetect Captcha library
    $this->load->library('botdetect/BotDetectSimpleCaptcha');

    $captchaCode = $this->input->post('captchaCode');
    $captchaId = $this->input->post('captchaId');

    // validate captcha
    $isHuman = $this->botdetectsimplecaptcha->Validate($captchaCode, $captchaId);

    if ($isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }

    // write the validation result as json string for sending it back to client
    $result = array('success' => $isHuman);

    return $this->output
      ->set_content_type('application/json')
      ->set_output(json_encode($result));
  }
}

Display Captcha error message in your Angular template

<div
  class="error"
  *ngIf="captchaCode.errors?.incorrectCaptcha && !captchaCode.pristine"
  >
  Incorrect captcha code.
</div>

Assuming you have used the correctCaptcha directive attribute in captcha code input field, to display captcha error message, simply check if incorrectCaptcha property exists in captchaCode.errors object. If it exists, this means that UI captcha validation failed.

PHP server-side Configuration

Install BotDetect PHP Captcha library on Server-side

Before integrating BotDetect Captcha in your Angular application, you need to ensure you have installed BotDetect PHP Captcha library on your server where your Angular application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?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.3.xsd">

    <captchaStyles>
        <captchaStyle>
            <name>exampleCaptcha</name>
            <userInputID>captchaCode</userInputID>
            <codeLength>3-5</codeLength>
            <helpLinkMode>Image</helpLinkMode>
        </captchaStyle>

        <captchaStyle>
            <name>loginCaptcha</name>
            <userInputID>captchaCode</userInputID>
            <codeLength>4-6</codeLength>
            <helpLinkMode>Image</helpLinkMode>
        </captchaStyle>
    </captchaStyles>

</botdetect>

All BotDetect captcha options will be configured in config/botdetect.xml configuration file. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

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

Integration in AngularJS application -- Introduction

BotDetect Captcha protection can be added to your AngularJS applications using the BotDetect CAPTCHA AngularJS Module. Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

and using validateUnsafe(callback) method to validate Captcha code on form submit:

app.controller('ExampleController', function($scope, Captcha) {

  // On form submit.
  $scope.validate = function() {

    var captcha = new Captcha();

    captcha.validateUnsafe(function(isCaptchaCodeCorrect) {

      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }

    });
  };
   
});

PLEASE NOTE: Since Captcha protects some server-side action, a Captcha code needs to be validated again on the server-side -- in your backend tech specific way -- before that protected action is executed.

You can see how BotDetect Captcha protection is added to a simple AngularJS form by running the BotDetect Captcha integration code examples coming with the each BotDetect product's free download package.

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

Integration in AngularJS application

AngularJS app with ASP.NET backend

Install BotDetect CAPTCHA AngularJS Module

Step 1: Install BotDetect Captcha AngularJS Module

Step 2: Include BotDetect Captcha AngularJS Module in your web app

<script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>

Step 3: Add BotDetect Captcha AngularJS Module to your AngularJS module

The following step ensures that BotDetect CAPTCHA library works properly in your AngularJS application. Please follow it carefully.

var app = angular.module('app', ['BotDetectCaptcha']);

app.config(function(captchaSettingsProvider) {
  ...
  
  captchaSettingsProvider.setSettings({
    captchaEndpoint: 'captcha-endpoint/BotDetectCaptcha.ashx'
  });
});

We add BotDetectCaptcha module to your AngularJS module as a dependency. It requires to configure BotDetect ASP.NET Captcha path to captchaEndpoint setting and in order to do this, in config function, we inject captchaSettingsProvider and then invoke setSettings() function as the code right above.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect ASP.NET Captcha library. If you deployed BotDetect ASP.NET Captcha library in the root of your domain, then you don't need to set this path.
  • /BotDetectCaptcha.ashx: is HttpHandler path, which is described on Register BotDetect HttpHandler for CAPTCHA Requests guide below.

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/BotDetectCaptcha.ashx (replace the exact path of your domain). If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha who responded error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your AngularJS Template

Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

BotDetect Captcha AngularJS Module provides botdetect-captcha element to add Captcha in your forms. It has styleName attribute, which you can assign it a captcha style name defined in botdetect.xml configuration file.

Captcha Validation

Client-side Captcha validation in your AngularJS application

BotDetect Captcha AngularJS Module provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
app.controller('ExampleController', function($scope, Captcha) {

  // On form submit.
  $scope.validate = function() {

    var captcha = new Captcha();

    captcha.validateUnsafe(function(isCaptchaCodeCorrect) {

      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }

    });
  };
   
});

OR:

  • Using correct-captcha directive attribute to validate Captcha code on blur event:
<input 
  type="text" 
  id="captchaCode"
  name="captchaCode"
  ng-model="captchaCode" 
  correct-captcha
>

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

ASP.NET Server-side Captcha validation

var app = angular.module('app', ['BotDetectCaptcha']);

...

app.controller('ExampleController', function($scope, $http, Captcha) {

  var exampleUrl = '/your-server-side-api-url';
  
  $scope.validate = function(valid) {

    if (!valid) {
      return;
    }

    // create new BotDetect Captcha instance
    var captcha = new Captcha();
    
    // captcha id for validating captcha at server-side
    var captchaId = captcha.captchaId;
    
    // captcha code input value for validating captcha at server-side
    var captchaCode = $scope.captchaCode;

    var postData = {
      captchaId: captchaId,
      captchaCode: captchaCode
    };
    
    $http({
      method: 'POST',
      url: exampleUrl,
      dataType: 'json',
      contentType: 'application/json',
      data: JSON.stringify(postData)
    })
      .then(function(response) {
        if (response.data.success) {
          // CAPTCHA validation passed at server-side
        } else {
          // CAPTCHA validation falied at client-side
        }
        
        // reload Captcha image
        captcha.reloadImage();
      }, function(error) {
        throw new Error(error.data);
      });
  };
   
});

In the code above, we inject Captcha service into ExampleController. The Captcha service exposes all Captcha workflow functions and vars that we will use during the form submission part of the workflow.

To validate Captcha at server-side, we need to send captchaId property of Captcha service and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of Captcha service. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in Web API 2:
using BotDetect.Web;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace ProductApp.Controllers
{
    public class ExampleController : ApiController
    {
        // POST api/example
        public HttpResponseMessage Post([FromBody]Models.BasicForm value)
        {
            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(value.CaptchaCode, value.CaptchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            string jsonString = JsonConvert.SerializeObject(validationResult);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            return response;
        }
    }
}
  • Server-side Captcha validation in a Generic Handler:
<%@ WebHandler Language="C#" Class="BasicHandler" %>
using System;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BotDetect.Web;

public class BasicHandler : 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 captchaId = formDataObj["captchaId"];
            string captchaCode = formDataObj["captchaCode"];

            // validate captcha
            SimpleCaptcha captcha = new SimpleCaptcha();
            bool isHuman = captcha.Validate(captchaCode, captchaId);

            if (isHuman)
            {
                // Captcha validation passed
                // TODO: do whatever you want here
            }

            // the object that stores validation result
            Dictionary<string, bool> validationResult = new Dictionary<string, bool>();
            validationResult.Add("success", isHuman);

            // write the validation result as json string for sending it back to client
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(JsonConvert.SerializeObject(validationResult));
        }
    }
}

Display Captcha error message in your AngularJS template

<div 
  class="error" 
  ng-show="exampleForm.captchaCode.$invalid && !exampleForm.captchaCode.$pristine"
  >
  Incorrect captcha code.
</div>

Assuming you have used the correct-code directive attribute in captcha code input field, to display captcha error message, simply check $invalid of captchaCode. If it returns true, this means that UI captcha validation failed.

ASP.NET server-side Configuration

Install BotDetect ASP.NET Captcha library on Server-side

Before integrating BotDetect Captcha in your Angular application, you need to ensure you have installed BotDetect ASP.NET Captcha library on your server where your Angular application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?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.0.xsd">

  <captchaStyles>
    
    <captchaStyle>
      <name>exampleCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>6</codeLength>
    </captchaStyle>

    <captchaStyle>
      <name>loginCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>4-6</codeLength>
      <codeStyle>Alphanumeric</codeStyle>
    </captchaStyle>

  </captchaStyles>

</botdetect>

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in root folder of your project. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

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

AngularJS app with JAVA backend

Install BotDetect CAPTCHA AngularJS Module

Step 1: Install BotDetect Captcha AngularJS Module

Step 2: Include BotDetect Captcha AngularJS Module in your web app

<script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>

Step 3: Add BotDetect Captcha AngularJS Module to your AngularJS module

The following step ensures that BotDetect CAPTCHA library works properly in your AngularJS application. Please follow it carefully.

var app = angular.module('app', ['BotDetectCaptcha']);

app.config(function(captchaSettingsProvider) {
  ...
  
  captchaSettingsProvider.setSettings({
    captchaEndpoint: 'captcha-endpoint/botdetectcaptcha'
  });
});

We add BotDetectCaptcha module to your AngularJS module as a dependency. It requires to configure BotDetect Java Captcha path to captchaEndpoint setting and in order to do this, in config function, we inject captchaSettingsProvider and then invoke setSettings() function as the code right above.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect Java Captcha library. If you deployed BotDetect Java Captcha library in the root of your domain, then you don't need to set this path.
  • /botdetectcaptcha: is SimpleCaptchaServlet path, which is described on Register SimpleCaptchaServlet guide below.

To ensure that you set the captchaEndpoint to right path, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/botdetectcaptcha (replace the 'yourdomain.com' with your domain). If opening the url in browser results with an error message ('unknown command') then you set the right path since it is the BotDetect Captcha that responded with 'unknown command' error. Otherwise, if you failed to set right path, then your server will respond with 404 instead.

Please note, in order to perform this check, BotDetect Captcha Generator needs to be deployed to your server (described in II. Captcha Generator server-side configuration).

Display BotDetect CAPTCHA In Your AngularJS Template

Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

BotDetect Captcha AngularJS Module provides botdetect-captcha element to add Captcha in your forms. It has styleName attribute, which you can assign it a captcha style name defined in botdetect.xml configuration file.

Captcha Validation

Client-side Captcha validation in your AngularJS application

BotDetect Captcha AngularJS Module provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
app.controller('ExampleController', function($scope, Captcha) {

  // On form submit.
  $scope.validate = function() {

    var captcha = new Captcha();

    captcha.validateUnsafe(function(isCaptchaCodeCorrect) {

      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }

    });
  };
   
});

OR:

  • Using correct-captcha directive attribute to validate Captcha code on blur event:
<input 
  type="text" 
  id="captchaCode"
  name="captchaCode"
  ng-model="captchaCode" 
  correct-captcha
>

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

JAVA Server-side Captcha validation

var app = angular.module('app', ['BotDetectCaptcha']);

...

app.controller('ExampleController', function($scope, $http, Captcha) {

  var exampleUrl = '/your-server-side-api-url';
  
  $scope.validate = function(valid) {

    if (!valid) {
      return;
    }

    // create new BotDetect Captcha instance
    var captcha = new Captcha();
    
    // captcha id for validating captcha at server-side
    var captchaId = captcha.captchaId;
    
    // captcha code input value for validating captcha at server-side
    var captchaCode = $scope.captchaCode;

    var postData = {
      captchaId: captchaId,
      captchaCode: captchaCode
    };
    
    $http({
      method: 'POST',
      url: exampleUrl,
      dataType: 'json',
      contentType: 'application/json',
      data: JSON.stringify(postData)
    })
      .then(function(response) {
        if (response.data.success) {
          // CAPTCHA validation passed at server-side
        } else {
          // CAPTCHA validation falied at client-side
        }
        
        // reload Captcha image
        captcha.reloadImage();
      }, function(error) {
        throw new Error(error.data);
      });
  };
   
});

In the code above, we inject Captcha service into ExampleController. The Captcha service exposes all Captcha workflow functions and vars that we will use during the form submission part of the workflow.

To validate Captcha at server-side, we need to send captchaId property of Captcha service and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of Captcha service. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in a Servlet is performed in the following way:
....

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

public class ExampleServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
   
    PrintWriter out = response.getWriter();
    Gson gson = new Gson();
    
    response.setContentType("application/json; charset=utf-8");
    
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(request.getReader());
    
    String captchaId = formDataObj.get("captchaId").getAsString();
    String captchaCode = formDataObj.get("captchaCode").getAsString();
    
    // validate captcha
    SimpleCaptcha captcha = SimpleCaptcha.load(request);
    boolean isHuman = captcha.validate(captchaCode, captchaId);
    
    if (isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }
    
    // the object that stores validation result
    ExampleValidationResult validationResult = new ExampleValidationResult();
    validationResult.setSuccess(isHuman);
    
    try {
      // write the validation result as json string for sending it back to client
      out.write(gson.toJson(validationResult));
    } catch(Exception ex) {
      out.write(ex.getMessage());
    } finally {
      out.close();
    }
  }
}
  • Server-side Captcha validation in a Spring MVC is performed in the following way:
...
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

@Controller
public class ExampleController {

  @RequestMapping(value = "basic-captcha", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
  @ResponseBody
  public String exampleCaptcha(HttpServletRequest request) {
    JsonParser parser = new JsonParser();
    JsonObject formDataObj = null;
    boolean result = false;

    try {
      formDataObj = (JsonObject) parser.parse(request.getReader());
    } catch (IOException ex) { }

    if (formDataObj != null) {
      String captchaId = formDataObj.get("captchaId").getAsString();
      String captchaCode = formDataObj.get("captchaCode").getAsString();

      // validate captcha
      SimpleCaptcha captcha = SimpleCaptcha.load(request);
      boolean isHuman = captcha.validate(captchaCode, captchaId);
      
      result = isHuman;
    }

    return "{\"success\":" + result.toString() + "}";
  }
}
  • Server-side Captcha validation in a Struts Action is performed in the following way:
...
import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class ExampleAction {

  private boolean success = false;

  public boolean isSuccess() {
    return success;
  }

  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    
    if (!request.getMethod().equalsIgnoreCase("post")) {
      return Action.ERROR;
    }

    Map<String, String> mapParams = request.getParameterMap();
    Set<String> setKeys = mapParams.keySet();
    Iterator<String> temp = setKeys.iterator();
    String data = temp.next();

    JsonParser parser = new JsonParser();
    JsonObject formDataObj = (JsonObject) parser.parse(data);

    if (formDataObj != null) {
      String captchaId = formDataObj.get("captchaId").getAsString();
      String captchaCode = formDataObj.get("captchaCode").getAsString();

      // validate captcha
      SimpleCaptcha captcha = SimpleCaptcha.load(request);
      boolean isHuman = captcha.validate(captchaCode, captchaId);
      
      this.success = isHuman;
    }

    return Action.SUCCESS;
  }
}

Display Captcha error message in your AngularJS template

<div 
  class="error" 
  ng-show="exampleForm.captchaCode.$invalid && !exampleForm.captchaCode.$pristine"
  >
  Incorrect captcha code.
</div>

Assuming you have used the correct-code directive attribute in captcha code input field, to display captcha error message, simply check $invalid of captchaCode. If it returns true, this means that UI captcha validation failed.

JAVA server-side Configuration

Install BotDetect Java Captcha library on Server-side

Before integrating BotDetect Captcha in your Angular application, you need to ensure you have installed BotDetect Java Captcha library on your server where your Angular application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?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.5.xsd">

  <captchaStyles>
    
    <captchaStyle>
      <name>exampleCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>6</codeLength>
    </captchaStyle>

    <captchaStyle>
      <name>loginCaptcha</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>4-6</codeLength>
      <codeStyle>ALPHANUMERIC</codeStyle>
    </captchaStyle>

  </captchaStyles>

</botdetect>

To configure captcha options, you need to create botdetect.xml configuration file (with xml content like the one above this) in WEB-INF/ folder. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

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

AngularJS app with PHP backend

Install BotDetect CAPTCHA AngularJS Module

Step 1: Install BotDetect Captcha AngularJS Module

Step 2: Include BotDetect Captcha AngularJS Module in your web app

<script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>

Step 3: Add BotDetect Captcha AngularJS Module to your AngularJS module

The following step ensures that BotDetect CAPTCHA library works properly in your AngularJS application. Please follow it carefully.

var app = angular.module('app', ['BotDetectCaptcha']);

app.config(function(captchaSettingsProvider) {
  ...
  
  captchaSettingsProvider.setSettings({
    captchaEndpoint: 'captcha-endpoint/simple-botdectect.php'
  });
});

We add BotDetectCaptcha module to your AngularJS module as a dependency. It requires to configure BotDetect PHP Captcha path to captchaEndpoint setting and in order to do this, in config function, we inject captchaSettingsProvider and then invoke setSettings() function as the code right above.

Before you set the path to captchaEndpoint setting, we need to clarify what we set here:

  • captcha-endpoint: is an example path, you need to set exact path to where you have deployed BotDetect PHP Captcha library. If you deployed BotDetect PHP Captcha library in the root of your domain, then you don't need to set this path.
  • This /simple-botdectect.php is the Handler URL of the PHP script processing Captcha challenge Http requests and this if you use the BotDetect Captcha library in a Plain PHP application. Use /simple-captcha-handler if you use the following:

To ensure that you have set a right path to captchaEndpoint setting, check it by opening the following url in your browser: http://yourdomain.com/captcha-endpoint/simple-botdetect.php (replace the exact path of your domain). If this results with an error message ("unknown command") then you set the right path, since that is the BotDetect Captcha that responded with error (when you fail to set correct path, then your server will respond with 404 instead). Please note, in order to perform this check, BotDetect Captcha Generator needs to be installed & deployed to your server.

Display BotDetect CAPTCHA In Your AngularJS Template

Displaying the Captcha challenge can be as simple as:

<botdetect-captcha styleName="exampleCaptcha"></botdetect-captcha>

BotDetect Captcha AngularJS Module provides botdetect-captcha element to add Captcha in your forms. It has styleName attribute, which you can assign it a captcha style name defined in botdetect.xml configuration file.

Captcha Validation

Client-side Captcha validation in your AngularJS application

BotDetect Captcha AngularJS Module provides two approaches to validate Captcha on client-side.

  • Using validateUnsafe(callback) method to validate Captcha code on form submit: PLEASE NOTE: Since Captcha protect some server-side action, a Captcha code needs to be validated again at the server-side -- in your backend tech specific way -- before that protected action is executed.
app.controller('ExampleController', function($scope, Captcha) {

  // On form submit.
  $scope.validate = function() {

    var captcha = new Captcha();

    captcha.validateUnsafe(function(isCaptchaCodeCorrect) {

      if (isCaptchaCodeCorrect) {
        // Captcha code is correct
      } else {
        // Captcha code is incorrect
      }

    });
  };
   
});

OR:

  • Using correct-captcha directive attribute to validate Captcha code on blur event:
<input 
  type="text" 
  id="captchaCode"
  name="captchaCode"
  ng-model="captchaCode" 
  correct-captcha
>

These client-side captcha validations are just an usability improvement that you may use or not -- they do not protect your form from spammers at all.

As you are protecting some server-side action you must validate a Captcha at the server-side before executing that protected action.

PHP Server-side Captcha validation

var app = angular.module('app', ['BotDetectCaptcha']);

...

app.controller('ExampleController', function($scope, $http, Captcha) {

  var exampleUrl = '/your-server-side-api-url';
  
  $scope.validate = function(valid) {

    if (!valid) {
      return;
    }

    // create new BotDetect Captcha instance
    var captcha = new Captcha();
    
    // captcha id for validating captcha at server-side
    var captchaId = captcha.captchaId;
    
    // captcha code input value for validating captcha at server-side
    var captchaCode = $scope.captchaCode;

    var postData = {
      captchaId: captchaId,
      captchaCode: captchaCode
    };
    
    $http({
      method: 'POST',
      url: exampleUrl,
      dataType: 'json',
      contentType: 'application/json',
      data: JSON.stringify(postData)
    })
      .then(function(response) {
        if (response.data.success) {
          // CAPTCHA validation passed at server-side
        } else {
          // CAPTCHA validation falied at client-side
        }
        
        // reload Captcha image
        captcha.reloadImage();
      }, function(error) {
        throw new Error(error.data);
      });
  };
   
});

In the code above, we inject Captcha service into ExampleController. The Captcha service exposes all Captcha workflow functions and vars that we will use during the form submission part of the workflow.

To validate Captcha at server-side, we need to send captchaId property of Captcha service and captcha code visitor submited to server-side.

Once request finished, we always reload Captcha by calling the reloadImage() function of Captcha service. This is needed to generate the new captcha code for the current captcha id.

At server-side API, we take captchaId and captchaCode values sent from client-side, and using Validate(captchaCode, captchaId) method of SimpleCaptcha instance we validate Captcha code. Finally, we write the validation result as json string for sending it back to client.

  • Server-side Captcha validation in Plain PHP:
<?php
require("captcha-endpoint/simple-botdetect.php");

// directly accessing this script is an error
if (!$_SERVER['REQUEST_METHOD'] == "POST") {
  header("HTTP/1.1 400 Bad Request");
  exit;
}

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$userInput = $input["captchaCode"];
$captchaId = $input["captchaId"];

// Captcha validation
$ExampleCaptcha = new SimpleCaptcha("exampleCaptcha");
$isHuman = $ExampleCaptcha->Validate($userInput, $captchaId);

if ($isHuman) {
  // Captcha validation passed
  // TODO: do whatever you want here
}
$result = array('success' => $isHuman);
echo json_encode($result, true);
exit;
  • Server-side Captcha validation in Symfony:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ExampleController extends Controller
{
  /**
   * @Route("/api/example", methods={"POST"})
   */
  public function postExampleAction(Request $request)
  {
    $postData = json_decode($request->getContent());
    
    $captchaCode = $postData->captchaCode;
    $captchaId = $postData->captchaId;

    // validate captcha
    $captcha = $this->container->get('simple_captcha')->getInstance();
    $isHuman = $captcha->Validate($captchaCode, $captchaId);
    
    if ($isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }

    // write the validation result as json string for sending it back to client
    $response = array('success' => $isHuman);
    return $this->json($response);
  }
}
  • Server-side Captcha validation in Laravel:
<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ExampleController extends Controller
{
  public function postAction(Request $request)
  {
    $captchaCode = $request->input('captchaCode');
    $captchaId = $request->input('captchaId');
    
    // validate captcha
    $isHuman = simple_captcha_validate($captchaCode, $captchaId);

    if ($isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }
   
    // write the validation result as json string for sending it back to client
    $response = array('success' => $isHuman);
    return response()->json($response);
  }
}
  • Server-side Captcha validation in CakePHP:
<?php 

namespace App\Controller;

use Cake\Controller\Controller;

class ExampleController extends Controller
{
  public function initialize()
  {
    parent::initialize();

    // load the Simple Captcha component
    $this->loadComponent('CakeCaptcha.SimpleCaptcha');
  }

  public function postExampleAction()
  {
    $this->autoRender = false;
    
    if ($this->request->is('post')) {
      $captchaCode = $this->request->data['captchaCode'];
      $captchaId = $this->request->data['captchaId'];
      
      // validate captcha
      $isHuman = simple_captcha_validate($captchaCode, $captchaId);

      if ($isHuman) {
        // Captcha validation passed
        // TODO: do whatever you want here
      }

      // write the validation result as json string for sending it back to client
      $result = array('success' => $isHuman);
      return $this->response->withType('application/json')
              ->withStringBody(json_encode($result));
    }
  }
}
  • Server-side Captcha validation in CodeIgniter:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Example extends CI_Controller {

  public function postExampleAction()
  {
    // load the BotDetect Captcha library
    $this->load->library('botdetect/BotDetectSimpleCaptcha');

    $captchaCode = $this->input->post('captchaCode');
    $captchaId = $this->input->post('captchaId');

    // validate captcha
    $isHuman = $this->botdetectsimplecaptcha->Validate($captchaCode, $captchaId);

    if ($isHuman) {
      // Captcha validation passed
      // TODO: do whatever you want here
    }

    // write the validation result as json string for sending it back to client
    $result = array('success' => $isHuman);

    return $this->output
      ->set_content_type('application/json')
      ->set_output(json_encode($result));
  }
}

Display Captcha error message in your AngularJS template

<div 
  class="error" 
  ng-show="exampleForm.captchaCode.$invalid && !exampleForm.captchaCode.$pristine"
  >
  Incorrect captcha code.
</div>

Assuming you have used the correct-code directive attribute in captcha code input field, to display captcha error message, simply check $invalid of captchaCode. If it returns true, this means that UI captcha validation failed.

PHP server-side Configuration

Install BotDetect PHP Captcha library on Server-side

Before integrating BotDetect Captcha in your Angular application, you need to ensure you have installed BotDetect PHP Captcha library on your server where your Angular application back end is hosted. Here is where you can find how:

Configure BotDetect Captcha options

<?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.3.xsd">

    <captchaStyles>
        <captchaStyle>
            <name>exampleCaptcha</name>
            <userInputID>captchaCode</userInputID>
            <codeLength>3-5</codeLength>
            <helpLinkMode>Image</helpLinkMode>
        </captchaStyle>

        <captchaStyle>
            <name>loginCaptcha</name>
            <userInputID>captchaCode</userInputID>
            <codeLength>4-6</codeLength>
            <helpLinkMode>Image</helpLinkMode>
        </captchaStyle>
    </captchaStyles>

</botdetect>

All BotDetect captcha options will be configured in config/botdetect.xml configuration file. The full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Please Note

Angular Captcha Module requires the new experimental Simple API that is currently available in BotDetect Java v4.0.Beta3+, BotDetect PHP v4.2.0+, as well as in BotDetect ASP.NET v4.4.0 build for legacy .NET.
The Simple API for ASP.NET Core will be available in the BotDetect ASP.NET v4.4.1 that will be released in few weeks time.

Current BotDetect Versions