Angular & AngularJS Captcha Modules: Step-by-step Integration Guides
Unlike Recaptcha the Stalker -- BotDetect CAPTCHA works in China! Licensable source-code; self-hosted -- doesn't stalk -- nor does it slurp your form-data! Think: GDPR & LGPD!
Click on the link below that matches the Angular version used by your frontend:
..............................................................
Angular 2/4/5/6/7/8-based Frontend
Click on the link below that matches your BotDetect CAPTCHA Angular Module usage scenario:
- Angular-based Frontend and an ASP.NET Core-based Backend
- Angular-based Frontend and a legacy ASP.NET-based Backend
- Angular-based Frontend and a Java-based Backend
- Angular-based Frontend and a PHP-based Backend
..............................................................
Angular-based Frontend and the web API with MVC Core 1/2 on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a Angular-based frontend and the web API with ASP.NET Core MVC on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
Path
Add the BotDetect
section into your /your-app-backend-folder/appsettings.json
file:
{ "BotDetect" : { "CaptchaEndpointPath" : "simple-captcha-endpoint.ashx" } }
Add the highlighted lines into your app's Startup
class (Startup.cs
):
public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... // configure your application pipeline to use SimpleCaptcha middleware app.UseSimpleCaptcha(Configuration.GetSection("BotDetect")); ... } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Comment the next line if your app is running on the .NET Core 2.0 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddMemoryCache(); // Adds a default in-memory // implementation of // IDistributedCache // Add framework services. services.AddMvc(); } }
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- web API with MVC Core Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The corrensponding properties must be added to YourFormModel
:
public class YourFormModel { public string CaptchaId { get; set; } public string UserEnteredCaptchaCode { get; set; } }
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the C# code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path using BotDetect.Web; using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("your-app-backend-path")] public class YourFormController : Controller { [HttpPost] public IActionResult Post([FromBody] Models.YourFormModel value) { string userEnteredCaptchaCode = value.UserEnteredCaptchaCode; string captchaId = value.CaptchaId; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt return Content("{\"success\":false}", "application/json; charset=utf-8"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & web api with mvc core 1/2 backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and the legacy ASP.NET MVC on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a Angular-based frontend and the legacy ASP.NET MVC (MVC1-5) on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
path
Register the simple-captcha-endpoint.ashx
path, and map it to the SimpleCaptchaHandler
, by adding the highlighted lines from the
snippet below into your app's web.config
file.
<system.web> <httpHandlers> <!-- register the HttpHandler that serves BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer>
Configure your app's router to do not process simple-captcha-endpoint.ashx
requests by adding the following line into your
App_Start\RouteConfig.cs
file:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // BotDetect requests must not be routed routes.IgnoreRoute("{*botdetect}", new { botdetect = @"(.*)simple-captcha-endpoint\.ashx" }); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Example", action = "Index", id =UrlParameter.Optional } ); } }
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- legacy ASP.NET MVC 1-5 Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The corrensponding properties must be added to YourFormModel
:
public class YourFormModel { public string CaptchaId { get; set; } public string UserEnteredCaptchaCode { get; set; } }
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here are the C# and VB.NET code snippets:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] using BotDetect.Web; namespace App.Controllers { public class YourFormController : Controller { [HttpPost] public ContentResult PostAction(YourFormModel yourFormModel) { string userEnteredCaptchaCode = yourFormModel.UserEnteredCaptchaCode; string captchaId = yourFormModel.CaptchaId; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt return Content("{\"success\":false}", "application/json; charset=utf-8"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & .net mvc-based backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and the legacy ASP.NET Web-API 2 on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a Angular-based frontend and the legacy ASP.NET Web-API 2 on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
path
Register the simple-captcha-endpoint.ashx
path, and map it to the SimpleCaptchaHandler
, by adding the highlighted lines from the
snippet below into your app's web.config
file.
<system.web> <httpHandlers> <!-- register the HttpHandler that serves BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer>
Configure your app's router to do not process simple-captcha-endpoint.ashx
requests by adding the following line into your
App_Start\WebApiConfig.cs
file:
config.Routes.IgnoreRoute("botdetect", @"(.*)simple-captcha-endpoint\.ashx");
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- legacy ASP.NET WebAPI2 Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The corrensponding properties must be added to YourFormModel
:
public class YourFormModel { public string CaptchaId { get; set; } public string UserEnteredCaptchaCode { get; set; } }
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here are the C# and VB.NET code snippets:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using Newtonsoft.Json; using BotDetect.Web; namespace App.Controllers { public class YourFormController : ApiController { public HttpResponseMessage Post([FromBody]Models.YourFormModel value) { string userEnteredCaptchaCode = value.UserEnteredCaptchaCode; string captchaId = value.CaptchaId; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent("{\"success\":false}", Encoding.UTF8, "application/json"); return response; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & .net web-api 2 backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and the legacy ASP.NET Generic Handler on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a Angular-based frontend and the legacy ASP.NET Generic Handler on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
path
Register the simple-captcha-endpoint.ashx
path, and map it to the SimpleCaptchaHandler
, by adding the highlighted lines from the
snippet below into your app's web.config
file.
<system.web> <httpHandlers> <!-- register the HttpHandler that serves BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- legacy ASP.NET Generic Handler Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here are the C# and VB.NET code snippets:
<%@ WebHandler Language="C#" Class="yourFormPostHandler" %> // route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path using System; using System.Web; using System.IO; using Newtonsoft.Json; using System.Collections.Generic; using BotDetect.Web; public class YourFormPostHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { if (HttpContext.Current.Request.HttpMethod == "POST") { string dataJson = new StreamReader(context.Request.InputStream).ReadToEnd(); Dictionary<string, string> formDataObj = new Dictionary<string, string>(); formDataObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataJson); string userEnteredCaptchaCode = formDataObj["userEnteredCaptchaCode"]; string captchaId = formDataObj["captchaId"]; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt context.Response.ContentType = "application/json; charset=utf-8"; context.Response.Write("{\"success\":false}"); return; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & asp.net generic handler backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and Java Servlet on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other Java Captcha Options
Step-1) Installation:
To protect an application that has a Angular-based frontend and Servlet on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect Java CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend
Install BotDetect Java CAPTCHA dependencies
The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.
To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines
to your app's backend pom.xml
file:
<repository> <id>captcha</id> <name>BotDetect Captcha Repository</name> <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url> </repository>
Then, declare the BotDetect dependency in your app's backend pom.xml
file, too:
<dependency> <groupId>com.captcha</groupId> <artifactId>botdetect-servlet</artifactId> <version>4.0.beta3.7</version> </dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/WEB-INF/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/java" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/java https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint
path
Update your application configuration:
Register the simple-captcha-endpoint
path, and map it to the SimpleCaptchaServlet
, by adding the highlighted lines from the
snippet below into your app's web.xml
file.
<servlet> <servlet-name>BotDetect Captcha</servlet-name> <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BotDetect Captcha</servlet-name> <url-pattern>/simple-captcha-endpoint</url-pattern> </servlet-mapping>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- Servlet Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the Java code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] import com.captcha.botdetect.web.servlet.SimpleCaptcha; public class YourFormPostServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonParser parser = new JsonParser(); JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); String captchaId = formDataObj.get("captchaId").getAsString(); // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request); // execute the captcha validation boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt response.setContentType("application/json; charset=utf-8"); response.getWriter().write("{\"success\":false}"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } }
Step-4) Configuring the Other Captcha Options
All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & java servlet backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and Java Spring on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other Java Captcha Options
Step-1) Installation:
To protect an application that has a Angular-based frontend and Spring on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect Java CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend
Install BotDetect Java CAPTCHA dependencies
The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.
To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines
to your app's backend pom.xml
file:
<repository> <id>captcha</id> <name>BotDetect Captcha Repository</name> <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url> </repository>
Then, declare the BotDetect dependency in your app's backend pom.xml
file, too:
<dependency> <groupId>com.captcha</groupId> <artifactId>botdetect-servlet</artifactId> <version>4.0.beta3.7</version> </dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/WEB-INF/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/java" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/java https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint
path
Update your application configuration:
Register the simple-captcha-endpoint
path, and map it to the SimpleCaptchaServlet
, by adding the highlighted lines from the
snippet below into your app's web.xml
file.
<servlet> <servlet-name>BotDetect Captcha</servlet-name> <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BotDetect Captcha</servlet-name> <url-pattern>/simple-captcha-endpoint</url-pattern> </servlet-mapping>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- Spring Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the Java code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] import com.captcha.botdetect.web.servlet.SimpleCaptcha; @Controller public class YourFormPostController { @RequestMapping(value = "your-app-backend-path", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody public String yourFormPostAction(HttpServletRequest request) throws IOException { JsonParser parser = new JsonParser(); JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); String captchaId = formDataObj.get("captchaId").getAsString(); // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request); // execute the captcha validation boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt return "{\"success\":false}"; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } }
Step-4) Configuring the Other Captcha Options
All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & java spring backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and Java Struts on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other Java Captcha Options
Step-1) Installation:
To protect an application that has a Angular-based frontend and Struts on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect Java CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend
Install BotDetect Java CAPTCHA dependencies
The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.
To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines
to your app's backend pom.xml
file:
<repository> <id>captcha</id> <name>BotDetect Captcha Repository</name> <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url> </repository>
Then, declare the BotDetect dependency in your app's backend pom.xml
file, too:
<dependency> <groupId>com.captcha</groupId> <artifactId>botdetect-servlet</artifactId> <version>4.0.beta3.7</version> </dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/WEB-INF/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/java" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/java https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint
path
Update your application configuration:
Register the simple-captcha-endpoint
path, and map it to the SimpleCaptchaServlet
, by adding the highlighted lines from the
snippet below into your app's web.xml
file.
<servlet> <servlet-name>BotDetect Captcha</servlet-name> <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BotDetect Captcha</servlet-name> <url-pattern>/simple-captcha-endpoint</url-pattern> </servlet-mapping>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- Struts Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the Java code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] import com.captcha.botdetect.web.servlet.SimpleCaptcha; public class YourFormPostAction extends ActionSupport { public String execute() throws IOException { HttpServletRequest request = ServletActionContext.getRequest(); if (!request.getMethod().equals("POST")) { return Action.ERROR; } JsonParser parser = new JsonParser(); JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); String captchaId = formDataObj.get("captchaId").getAsString(); // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request); // execute the captcha validation boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/json; charset=utf-8"); response.getWriter().write("{\"success\":false}"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } }
Step-4) Configuring the Other Captcha Options
All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & java struts backend section]
[back to top of angular section]
..............................................................
Angular-based Frontend and the plain PHP on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other PHP Captcha Options
Step-1) Installation
To protect an application that has a Angular-based frontend and the plain PHP on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA Angular Module
- App's backend: BotDetect PHP CAPTCHA Library
Step-1.1) Install BotDetect CAPTCHA Angular Module in Your App's Frontend
Install the BotDetect CAPTCHA Angular Module in the Angular version appropriate way:
Run the following command:
npm install angular-captcha --save
and add the following lines into the import section of your app's app.module.ts
file:
import { BotDetectCaptchaModule } from 'angular-captcha'; ... @NgModule({ declarations: [ ... ], imports: [ // import the Angular Captcha Module BotDetectCaptchaModule, ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step-1.2) Install BotDetect PHP CAPTCHA Library in Your App's Backend
Install BotDetect PHP CAPTCHA Library
Download the BotDetect PHP CAPTCHA library. The downloaded zip file contains the
botdetect-captcha-lib
folder with BotDetect PHP CAPTCHA library. Copy it into the root folder of the app's backend.
The final backend folder structure should look in the following way: /your-app-backend-folder/botdetect-captcha-lib/
Reconfigure BotDetect CAPTCHA PHP Library's Server-side Persistence Mechanism, If Needed
By default, BotDetect PHP CAPTCHA uses SQLite3 as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
Please Note
If you use Windows for development you will have to enable the SQLite3 PHP extension (php_sqlite3.dll) in php.ini. Unlike elsewhere, it is not enabled by default on Windows.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite3 -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- Angular Captcha Module on frontend has to be connected with the BotDetect PHP CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Add them to the botdetect.xml
that can be found at:/your-app-backend-folder/botdetect-captcha-lib/config/botdetect.xml
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/php" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/php https://captcha.com/schema/php/botdetect-4.2.5.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Place Captcha in Your Form
To the your-form-with-captcha.component.html
file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" name="yourFirstCaptchaUserInput" ngModel #yourFirstCaptchaUserInput="ngModel" type="text" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.3) Set the captchaEndpoint
in Your App's Frontend
Set the captchaEndpoint
property to point to the captcha endpoint path on your app's backend by adding the highlighted lines into your
app's your-form-with-captcha.component.ts
file:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/botdetect-captcha-lib/simple-botdetect.php'; }
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- Angular Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
In Angular applications that frontend functionality is spread over the following two source files:
your-form-with-captcha.component.ts
file -- captcha data collection, post triggering, and subsequent captcha validation result processingyour-form-with-captcha.component.service
file -- actual json-formatted data posting
Here is the your-form-with-captcha.component.ts
file example:
import { Component, ViewChild } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { CaptchaComponent } from 'angular-captcha'; import { YourFormWithCaptchaService } from './your-form-with-captcha.service'; @Component({ moduleId: module.id, selector: 'your-form-with-captcha', templateUrl: 'your-form-with-captcha.component.html', styleUrls: ['your-form-with-captcha.component.css'], providers: [YourFormWithCaptchaService] }) export class YourFormWithCaptchaComponent { @ViewChild(CaptchaComponent, { static: true }) captchaComponent: CaptchaComponent; constructor( private yourFormWithCaptchaService: YourFormWithCaptchaService ) { } ngOnInit(): void { // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend this.captchaComponent.captchaEndpoint = 'https://your-app-backend-hostname.your-domain.com/botdetect-captcha-lib/simple-botdetect.php'; } // Process the form on submit event. validate(value, valid): void { // get the user-entered captcha code value to be validated at the backend side let userEnteredCaptchaCode = this.captchaComponent.userEnteredCaptchaCode; // get the id of a captcha instance that the user tried to solve let captchaId = this.captchaComponent.captchaId; const postData = { userEnteredCaptchaCode: userEnteredCaptchaCode, captchaId: captchaId }; // post the captcha data to the backend this.yourFormWithCaptchaService.send(postData) .subscribe( response => { if (response.success == false) { // captcha validation failed; reload image this.captchaComponent.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }); } }
Here is the your-form-with-captcha.component.service
file example:
import { Injectable } from '@angular/core'; import { HttpHeaders, HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class YourFormWithCaptchaService { constructor(private http: HttpClient) { } send(data: Object): Observable<any> { const options = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) }; return this.http.post( 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data, options); } }
Step-3.2) Captcha Validation -- the plain PHP Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the:
Validate($userEnteredCaptchaCode, $captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the PHP code snippet:
<?php header('Content-Type: application/json; charset=utf-8'); // route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path if ($_SERVER['REQUEST_METHOD'] === 'POST') { require('botdetect-captcha-lib/simple-botdetect.php'); $postedData = (array) json_decode(file_get_contents('php://input'), true); $userEnteredCaptchaCode = $postedData['userEnteredCaptchaCode']; $captchaId = $postedData['captchaId']; // create a captcha instance to be used for the captcha validation $yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation $isHuman = $yourFirstCaptcha->Validate($userEnteredCaptchaCode, $captchaId); if ($isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt echo "{\"success\":false}"; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } }
Step-4) Configuring the Other PHP Captcha Options
All BotDetect PHP CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angular & plain php backend section]
[back to top of angular section]
..............................................................
Please Note
The new experimental Simple API is still work-in-progress. This Integration Guide & Examples require you to have the Angular Captcha Module v3.7.4 or AngularJS Captcha Module v1.6.1 on frontend, and one of the following BotDetect CAPTCHA releases on backend: ASP.NET v4.4.2+, Java v4.0.Beta3.7+, PHP v4.2.5+.
Unlike Recaptcha the Stalker -- BotDetect CAPTCHA works in China! Licensable source-code; self-hosted -- doesn't stalk -- nor does it slurp your form-data! Think: GDPR & LGPD!
Click on the link below that matches the Angular version used by your frontend:
..............................................................
AngularJS-based Frontend
Click on the link below that matches your BotDetect CAPTCHA AngularJS Module usage scenario:
- Angular-based Frontend and an ASP.NET Core-based Backend
- Angular-based Frontend and a legacy ASP.NET-based Backend
- Angular-based Frontend and a Java-based Backend
- Angular-based Frontend and a PHP-based Backend
..............................................................
AngularJS-based Frontend and the web API with MVC Core 1/2 on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a AngularJS-based frontend and the web API with ASP.NET Core MVC on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
Path
Add the BotDetect
section into your /your-app-backend-folder/appsettings.json
file:
{ "BotDetect" : { "CaptchaEndpointPath" : "simple-captcha-endpoint.ashx" } }
Add the highlighted lines into your app's Startup
class (Startup.cs
):
public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... // configure your application pipeline to use SimpleCaptcha middleware app.UseSimpleCaptcha(Configuration.GetSection("BotDetect")); ... } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Comment the next line if your app is running on the .NET Core 2.0 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddMemoryCache(); // Adds a default in-memory // implementation of // IDistributedCache // Add framework services. services.AddMvc(); } }
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- web API with MVC Core Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The corrensponding properties must be added to YourFormModel
:
public class YourFormModel { public string CaptchaId { get; set; } public string UserEnteredCaptchaCode { get; set; } }
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the C# code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path using BotDetect.Web; using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("your-app-backend-path")] public class YourFormController : Controller { [HttpPost] public IActionResult Post([FromBody] Models.YourFormModel value) { string userEnteredCaptchaCode = value.UserEnteredCaptchaCode; string captchaId = value.CaptchaId; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt return Content("{\"success\":false}", "application/json; charset=utf-8"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & web api with mvc core 1/2 backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and the legacy ASP.NET MVC on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a AngularJS-based frontend and the legacy ASP.NET MVC (MVC1-5) on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
path
Register the simple-captcha-endpoint.ashx
path, and map it to the SimpleCaptchaHandler
, by adding the highlighted lines from the
snippet below into your app's web.config
file.
<system.web> <httpHandlers> <!-- register the HttpHandler that serves BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer>
Configure your app's router to do not process simple-captcha-endpoint.ashx
requests by adding the following line into your
App_Start\RouteConfig.cs
file:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // BotDetect requests must not be routed routes.IgnoreRoute("{*botdetect}", new { botdetect = @"(.*)simple-captcha-endpoint\.ashx" }); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Example", action = "Index", id =UrlParameter.Optional } ); } }
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- legacy ASP.NET MVC 1-5 Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The corrensponding properties must be added to YourFormModel
:
public class YourFormModel { public string CaptchaId { get; set; } public string UserEnteredCaptchaCode { get; set; } }
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here are the C# and VB.NET code snippets:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] using BotDetect.Web; namespace App.Controllers { public class YourFormController : Controller { [HttpPost] public ContentResult PostAction(YourFormModel yourFormModel) { string userEnteredCaptchaCode = yourFormModel.UserEnteredCaptchaCode; string captchaId = yourFormModel.CaptchaId; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt return Content("{\"success\":false}", "application/json; charset=utf-8"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & .net mvc-based backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and the legacy ASP.NET Web-API 2 on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a AngularJS-based frontend and the legacy ASP.NET Web-API 2 on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
path
Register the simple-captcha-endpoint.ashx
path, and map it to the SimpleCaptchaHandler
, by adding the highlighted lines from the
snippet below into your app's web.config
file.
<system.web> <httpHandlers> <!-- register the HttpHandler that serves BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer>
Configure your app's router to do not process simple-captcha-endpoint.ashx
requests by adding the following line into your
App_Start\WebApiConfig.cs
file:
config.Routes.IgnoreRoute("botdetect", @"(.*)simple-captcha-endpoint\.ashx");
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- legacy ASP.NET WebAPI2 Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The corrensponding properties must be added to YourFormModel
:
public class YourFormModel { public string CaptchaId { get; set; } public string UserEnteredCaptchaCode { get; set; } }
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here are the C# and VB.NET code snippets:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using Newtonsoft.Json; using BotDetect.Web; namespace App.Controllers { public class YourFormController : ApiController { public HttpResponseMessage Post([FromBody]Models.YourFormModel value) { string userEnteredCaptchaCode = value.UserEnteredCaptchaCode; string captchaId = value.CaptchaId; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent("{\"success\":false}", Encoding.UTF8, "application/json"); return response; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & .net web-api 2 backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and the legacy ASP.NET Generic Handler on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other ASP.NET Captcha Options
Step-1) Installation
To protect an application that has a AngularJS-based frontend and the legacy ASP.NET Generic Handler on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect ASP.NET CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect ASP.NET CAPTCHA Library in Your App's Backend
Reference BotDetect ASP.NET CAPTCHA Component
The free version nuget is available on nuget.org
-- while the enterprise version nuget is available in the nuget
folder of the enterprise version installation and archive.
Run the following command in the Package Manager Console:
PM> Install-Package Captcha
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect ASP.NET CAPTCHA uses SQLite as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect ASP.NET CAPTCHA component on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/net https://captcha.com/schema/net/botdetect-4.4.2.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint.ashx
path
Register the simple-captcha-endpoint.ashx
path, and map it to the SimpleCaptchaHandler
, by adding the highlighted lines from the
snippet below into your app's web.config
file.
<system.web> <httpHandlers> <!-- register the HttpHandler that serves BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- register the HttpHandler that serves BotDetect Simple API requests (IIS 7+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint.ashx' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- legacy ASP.NET Generic Handler Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: Validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here are the C# and VB.NET code snippets:
<%@ WebHandler Language="C#" Class="yourFormPostHandler" %> // route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path using System; using System.Web; using System.IO; using Newtonsoft.Json; using System.Collections.Generic; using BotDetect.Web; public class YourFormPostHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { if (HttpContext.Current.Request.HttpMethod == "POST") { string dataJson = new StreamReader(context.Request.InputStream).ReadToEnd(); Dictionary<string, string> formDataObj = new Dictionary<string, string>(); formDataObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataJson); string userEnteredCaptchaCode = formDataObj["userEnteredCaptchaCode"]; string captchaId = formDataObj["captchaId"]; // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation bool isHuman = yourFirstCaptcha.Validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt context.Response.ContentType = "application/json; charset=utf-8"; context.Response.Write("{\"success\":false}"); return; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } } }
Step-4) Configuring the Other Captcha Options
All BotDetect ASP.NET CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & asp.net generic handler backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and Java Servlet on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other Java Captcha Options
Step-1) Installation:
To protect an application that has a AngularJS-based frontend and Servlet on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect Java CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend
Install BotDetect Java CAPTCHA dependencies
The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.
To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines
to your app's backend pom.xml
file:
<repository> <id>captcha</id> <name>BotDetect Captcha Repository</name> <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url> </repository>
Then, declare the BotDetect dependency in your app's backend pom.xml
file, too:
<dependency> <groupId>com.captcha</groupId> <artifactId>botdetect-servlet</artifactId> <version>4.0.beta3.7</version> </dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/WEB-INF/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/java" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/java https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint
path
Update your application configuration:
Register the simple-captcha-endpoint
path, and map it to the SimpleCaptchaServlet
, by adding the highlighted lines from the
snippet below into your app's web.xml
file.
<servlet> <servlet-name>BotDetect Captcha</servlet-name> <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BotDetect Captcha</servlet-name> <url-pattern>/simple-captcha-endpoint</url-pattern> </servlet-mapping>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- Servlet Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the Java code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] import com.captcha.botdetect.web.servlet.SimpleCaptcha; public class YourFormPostServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonParser parser = new JsonParser(); JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); String captchaId = formDataObj.get("captchaId").getAsString(); // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request); // execute the captcha validation boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt response.setContentType("application/json; charset=utf-8"); response.getWriter().write("{\"success\":false}"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } }
Step-4) Configuring the Other Captcha Options
All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & java servlet backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and Java Spring on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other Java Captcha Options
Step-1) Installation:
To protect an application that has a AngularJS-based frontend and Spring on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect Java CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend
Install BotDetect Java CAPTCHA dependencies
The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.
To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines
to your app's backend pom.xml
file:
<repository> <id>captcha</id> <name>BotDetect Captcha Repository</name> <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url> </repository>
Then, declare the BotDetect dependency in your app's backend pom.xml
file, too:
<dependency> <groupId>com.captcha</groupId> <artifactId>botdetect-servlet</artifactId> <version>4.0.beta3.7</version> </dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/WEB-INF/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/java" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/java https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint
path
Update your application configuration:
Register the simple-captcha-endpoint
path, and map it to the SimpleCaptchaServlet
, by adding the highlighted lines from the
snippet below into your app's web.xml
file.
<servlet> <servlet-name>BotDetect Captcha</servlet-name> <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BotDetect Captcha</servlet-name> <url-pattern>/simple-captcha-endpoint</url-pattern> </servlet-mapping>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- Spring Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the Java code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] import com.captcha.botdetect.web.servlet.SimpleCaptcha; @Controller public class YourFormPostController { @RequestMapping(value = "your-app-backend-path", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody public String yourFormPostAction(HttpServletRequest request) throws IOException { JsonParser parser = new JsonParser(); JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); String captchaId = formDataObj.get("captchaId").getAsString(); // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request); // execute the captcha validation boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt return "{\"success\":false}"; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } }
Step-4) Configuring the Other Captcha Options
All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & java spring backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and Java Struts on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other Java Captcha Options
Step-1) Installation:
To protect an application that has a AngularJS-based frontend and Struts on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect Java CAPTCHA library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect Java CAPTCHA Library in Your App's Backend
Install BotDetect Java CAPTCHA dependencies
The free version Maven artifacts are available from our public repository; while the enterprise version jars are available in the root folder of the enterprise version's archive.
To reference the BotDetect dependency from our public repository, the repository itself has to be declared first -- add the highlighted lines
to your app's backend pom.xml
file:
<repository> <id>captcha</id> <name>BotDetect Captcha Repository</name> <url>https://git.captcha.com/botdetect-java-captcha.git/blob_plain/HEAD:/</url> </repository>
Then, declare the BotDetect dependency in your app's backend pom.xml
file, too:
<dependency> <groupId>com.captcha</groupId> <artifactId>botdetect-servlet</artifactId> <version>4.0.beta3.7</version> </dependency>
Reconfigure BotDetect CAPTCHA Component's Server-side Persistence Mechanism, If Needed
By default, BotDetect Java CAPTCHA uses HSQLDB as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the HSQLDB -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect Java CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Create the /your-app-backend-folder/WEB-INF/botdetect.xml
file with the following content:
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/java" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/java https://captcha.com/schema/java/botdetect-4.0.beta3.7.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Register the simple-captcha-endpoint
path
Update your application configuration:
Register the simple-captcha-endpoint
path, and map it to the SimpleCaptchaServlet
, by adding the highlighted lines from the
snippet below into your app's web.xml
file.
<servlet> <servlet-name>BotDetect Captcha</servlet-name> <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BotDetect Captcha</servlet-name> <url-pattern>/simple-captcha-endpoint</url-pattern> </servlet-mapping>
Step-2.3) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.4) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/simple-captcha-endpoint' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- Struts Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the: validate(userEnteredCaptchaCode, captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the Java code snippet:
// route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path [...] import com.captcha.botdetect.web.servlet.SimpleCaptcha; public class YourFormPostAction extends ActionSupport { public String execute() throws IOException { HttpServletRequest request = ServletActionContext.getRequest(); if (!request.getMethod().equals("POST")) { return Action.ERROR; } JsonParser parser = new JsonParser(); JsonObject formDataObj = (JsonObject) parser.parse(request.getReader()); String userEnteredCaptchaCode = formDataObj.get("userEnteredCaptchaCode").getAsString(); String captchaId = formDataObj.get("captchaId").getAsString(); // create a captcha instance to be used for the captcha validation SimpleCaptcha yourFirstCaptcha = SimpleCaptcha.load(request); // execute the captcha validation boolean isHuman = yourFirstCaptcha.validate(userEnteredCaptchaCode, captchaId); if (isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/json; charset=utf-8"); response.getWriter().write("{\"success\":false}"); } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } } }
Step-4) Configuring the Other Captcha Options
All BotDetect Java CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & java struts backend section]
[back to top of angularjs section]
..............................................................
AngularJS-based Frontend and the plain PHP on Backend
- Step-1) Installation
- Step-2) Displaying Captcha in a Form
- Step-3) Captcha Validation
- Step-4) Configuring the Other PHP Captcha Options
Step-1) Installation
To protect an application that has a AngularJS-based frontend and the plain PHP on backend the following have to be installed:
- App's frontend: BotDetect CAPTCHA AngularJS Module
- App's backend: BotDetect PHP CAPTCHA Library
Step-1.1) Install BotDetect CAPTCHA AngularJS Module in Your App's Frontend
Install the BotDetect CAPTCHA AngularJS Module
npm install angularjs-captcha --save
and add the highlighted script include line into your app's index.html
file:
<script src="node_modules/angularjs/angular.min.js"></script> // the angularjs-captcha module requires angular itself to be included before, as above <script src="node_modules/angularjs-captcha/dist/angularjs-captcha.min.js"></script>
Step-1.2) Install BotDetect PHP CAPTCHA Library in Your App's Backend
Install BotDetect PHP CAPTCHA Library
Download the BotDetect PHP CAPTCHA library. The downloaded zip file contains the
botdetect-captcha-lib
folder with BotDetect PHP CAPTCHA library. Copy it into the root folder of the app's backend.
The final backend folder structure should look in the following way: /your-app-backend-folder/botdetect-captcha-lib/
Reconfigure BotDetect CAPTCHA PHP Library's Server-side Persistence Mechanism, If Needed
By default, BotDetect PHP CAPTCHA uses SQLite3 as its server-side persistence mechanism. If that fits your application's requirements you can skip this step.
Please Note
If you use Windows for development you will have to enable the SQLite3 PHP extension (php_sqlite3.dll) in php.ini. Unlike elsewhere, it is not enabled by default on Windows.
On the following links you can see how to reconfigure BotDetect to use Redis or Memcached instead of the SQLite3 -- if, per instance, your load-balanced application requires them.
Step-2) Displaying Captcha in a Form
To display a captcha in a form the following has to be done:
- Captcha style has to be defined.
- AngularJS Captcha Module on frontend has to be connected with the BotDetect PHP CAPTCHA library on backend.
Step-2.1) Define Your First Captcha Style
The most basic valid captcha style has to have the following two properties defined:
name
-- the name of a captcha style, anduserInputID
-- theID
of an<input>
element in which users will enter captcha codes
Add them to the botdetect.xml
that can be found at:/your-app-backend-folder/botdetect-captcha-lib/config/botdetect.xml
<?xml version="1.0" encoding="UTF-8"?> <botdetect xmlns="https://captcha.com/schema/php" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://captcha.com/schema/php https://captcha.com/schema/php/botdetect-4.2.5.xsd"> <captchaStyles> <captchaStyle> <name>yourFirstCaptchaStyle</name> <userInputID>yourFirstCaptchaUserInput</userInputID> </captchaStyle> </captchaStyles> </botdetect>
Step-2.2) Place Captcha in Your Form
To the your-form-with-captcha.html
AngularJS template file
-- at the exact place where you want to be displaying captcha challenges
-- add the following lines:
<botdetect-captcha captchaStyleName="yourFirstCaptchaStyle"></botdetect-captcha> <input id="yourFirstCaptchaUserInput" type="text" name="yourFirstCaptchaUserInput" ng-model="yourFirstCaptchaUserInput" >
Note that the values of both the captchaStyleName
and input id
attributes have to match the corresponding name
and userInputID
settings of a particular captcha style defined in the botdetect.xml
file.
Step-2.3) Set the captchaEndpoint
in Your App's Frontend
Inject the BotDetectCaptcha
module to your app's frontend; and set the captchaEndpoint property to point to the captcha endpoint path
on your app's backend -- by adding the highlighted parts into your app.js
file:
var app = angular.module('app', ['BotDetectCaptcha', 'ngRoute']); app.config(function ($routeProvider, captchaSettingsProvider) { $routeProvider .when('/your-form-with-captcha', { templateUrl: 'templates/your-form-with-captcha.html', controller: 'YourFormWithCaptchaController' }); // set the captchaEndpoint property to point to // the captcha endpoint path on your app's backend captchaSettingsProvider.setSettings({ captchaEndpoint: 'https://your-app-backend-hostname.your-domain.com/botdetect-captcha-lib/simple-botdetect.php' }); });
That is it. Open your form now. It should have a captcha rendered on it.
Please Note
Check the following FAQ item if your app's frontend and backend are on different hosts, and your browser blocks the requests to the captcha endpoint because of the CORS policy.
Step-3) Captcha Validation
To validate a captcha actions are needed on both the frontend and backend side.
Step-3.1) Captcha Validation -- AngularJS Frontend Code
A captcha validation starts with the frontend code posting the id of a captcha instance, and the corresponding captcha code value entered by an user, to your backend form processing code.
When that particular post request completes:
- If the captcha validation failed -- the
captcha.reloadImage()
needs to be called in order to generate a new captcha challenge. - If the captcha validation succeeded -- you proceed with your application workflow.
Here is an example of the YourFormWithCaptchaController.js
file with such a post and captcha validation result processing on the frontend side:
app.controller('YourFormWithCaptchaController', function ($scope, $http, $window, Captcha) { // process the form on submit event $scope.validate = function () { // create new AngularJS Captcha instance var captcha = new Captcha(); // get the user-entered captcha code value to be validated at the backend side var userEnteredCaptchaCode = captcha.getUserEnteredCaptchaCode(); // get the id of a captcha instance that the user tried to solve var captchaId = captcha.getCaptchaId(); var postData = { // add the user-entered captcha code value to the post data userEnteredCaptchaCode: userEnteredCaptchaCode, // add the id of a captcha instance to the post data captchaId: captchaId }; // post the captcha data to the /your-app-backend-path on your backend $http({ headers: { 'Content-Type': 'application/json; charset=utf-8' } method: 'POST', url: 'https://your-app-backend-hostname.your-domain.com/your-app-backend-path', data: postData }) .then(function (response) { if (response.data.success == false) { // captcha validation failed; reload image captcha.reloadImage(); // TODO: maybe display an error message, too } else { // TODO: captcha validation succeeded; proceed with the workflow } }, function (error) { throw new Error(error.data); }); }; });
Step-3.2) Captcha Validation -- the plain PHP Backend Code
The userEnteredCaptchaCode
and captchaId
values posted from the frontend are used to validate a captcha
challenge on the backend.
The validation is performed by calling the:
Validate($userEnteredCaptchaCode, $captchaId)
.
In this example, the result of validation is sent back to the frontend as a json.
Here is the PHP code snippet:
<?php header('Content-Type: application/json; charset=utf-8'); // route: // https://your-app-backend-hostname.your-domain.com/your-app-backend-path if ($_SERVER['REQUEST_METHOD'] === 'POST') { require('botdetect-captcha-lib/simple-botdetect.php'); $postedData = (array) json_decode(file_get_contents('php://input'), true); $userEnteredCaptchaCode = $postedData['userEnteredCaptchaCode']; $captchaId = $postedData['captchaId']; // create a captcha instance to be used for the captcha validation $yourFirstCaptcha = new SimpleCaptcha(); // execute the captcha validation $isHuman = $yourFirstCaptcha->Validate($userEnteredCaptchaCode, $captchaId); if ($isHuman == false) { // captcha validation failed; notify the frontend // TODO: consider logging the attempt echo "{\"success\":false}"; } else { // TODO: captcha validation succeeded; execute the protected action // TODO: do not forget to notify the frontend about the results } }
Step-4) Configuring the Other PHP Captcha Options
All BotDetect PHP CAPTCHA Simple API configuration options are set in the botdetect.xml
file -- while their descriptions are in the
Simple API configuration options page.
[back to the top of angularjs & plain php backend section]
[back to top of angularjs section]
Please Note
The new experimental Simple API is still work-in-progress. This Integration Guide & Examples require you to have the Angular Captcha Module v3.7.4 or AngularJS Captcha Module v1.6.1 on frontend, and one of the following BotDetect CAPTCHA releases on backend: ASP.NET v4.4.2+, Java v4.0.Beta3.7+, PHP v4.2.5+.
Current BotDetect Versions
-
BotDetect ASP.NET CAPTCHA
2019-07-22v4.4.2 -
BotDetect Java CAPTCHA
2019-07-22v4.0.Beta3.7 -
BotDetect PHP CAPTCHA
2019-07-22v4.2.5