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

  1. Integration in Angular application
    1. Angular 2/4/5/6/7+
    2. AngularJS 1.x
  2. Captcha Generator server-side configuration

I. Integration in Angular app

a) Angular 2/4/5/6/7+

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
      }
    });
  }

}

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.

Follows the step by step guide on how to integrate BotDetect into your Angular application. Backend related code snippets come in 3 different techs (.NET, Java & PHP) in order to cover whatever is the technology of your choice.

Install BotDetect CAPTCHA Angular Module

Step 1: Install BotDetect Captcha Angular Module

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:
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.

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.


b) AngularJS 1.x

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
      }

    });
  };
   
});

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.

Follows the step by step guide on how to integrate BotDetect into your AngularJS application. Backend related code snippets come in 3 different techs (.NET, Java & PHP) in order to cover whatever is the technology of your choice.

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:
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.

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.


II. Captcha Generator 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.

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