Captcha Session Storage
- Redis Session Storage
- ASP.NET Core on .NET Core with Redis Session Storage
- Legacy ASP.NET on Legacy .NET with Redis Session Storage
- Java with Redis Session Storage
- PHP with Redis Session Storage
- Memcached Session Storage
..............................................................
ASP.NET Core on .NET Core with Redis Session Storage
BotDetect ASP.NET Core Captcha Simple API uses StackExchange.Redis as Redis ASP.NET client, so you need to ensure StackExchange.Redis NuGet package was installed.
- Views\Example\Index.cshtml
- Controllers\ExampleController.cs
- Startup.cs
- appsettings.json
- botdetect.xml
Views\Example\Index.cshtml
@model CaptchaServerSidePersistenceInRedisExample.Models.ExampleModel @section header { <environment names="Development,Staging,Production"> <link rel="stylesheet" href="~/css/StyleSheet.css" /> </environment> } @{ ViewData["Title"] = "BotDetect ASP.NET CAPTCHA Options: Server Side Persistence in Redis Database Code Example"; } <h2>@ViewData["Title"].</h2> <h3>@ViewData["Message"]</h3> <div class="column"> <h1> BotDetect ASP.NET CAPTCHA Options: <br /> Basic ASP.NET MVC 6 Web Application CAPTCHA Server Side Persistence in Redis Database Code Example </h1> <form asp-controller="Example" asp-action="Index" method="post"> <fieldset> <legend>ASP.NET MVC 6 CAPTCHA Validation</legend> <div> <label asp-for="CaptchaCode">Retype the code from the picture:</label> <simple-captcha stylename="RedisCaptchaExample" /> <div class="actions"> <input asp-for="CaptchaCode" /> <input type="submit" value="Validate" /> <span asp-validation-for="CaptchaCode"></span> @if ((Context.Request.Method.ToUpper() == "POST") && ViewData.ModelState.IsValid) { <span class="correct">Correct!</span> } </div> </div> </fieldset> </form> </div>
Controllers\ExampleController.cs
using CaptchaServerSidePersistenceInRedisExample.Models; using BotDetect.Web.Mvc; using Microsoft.AspNetCore.Mvc; namespace CaptchaServerSidePersistenceInRedisExample.Controllers { public class ExampleController : Controller { public IActionResult Index() { return View(); } [HttpPost] [SimpleCaptchaValidation("CaptchaCode", "RedisCaptchaExample", "Incorrect!")] public IActionResult Index(ExampleModel model) { return View(model); } public IActionResult Error() { return View(); } } }
Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using BotDetect.Web; using Microsoft.Extensions.DependencyInjection.Extensions; using BotDetect.Web.Http; namespace CaptchaServerSidePersistenceInRedisExample { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddMemoryCache(); // Adds a default in-memory implementation of IDistributedCache // Add framework services. services.AddMvc(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Example/Error"); } app.UseStaticFiles(); //configure BotDetectCaptcha app.UseSimpleCaptcha(Configuration.GetSection("BotDetect")); app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller=Example}/{action=Index}"); routes.MapRoute( name: "default", template: "{controller=Example}/{action=Index}/{id?}"); }); } } }
appsettings.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } }, "BotDetect": { "CaptchaEndpointPath": "simple-captcha-endpoint.ashx" } }
Register simple-captcha-endpoint.ashx
used for BotDetect Captcha requests.
botdetect.xml
<?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-<!--CONTENTHOOK-BEGIN:string-->BD4_NET_TC<!--CONTENTHOOK-END-->.xsd"> <captchaStyles> <captchaStyle> <name>RedisCaptchaExample</name> <userInputID>CaptchaCode</userInputID> <codeLength>3</codeLength> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>Redis</persistenceType> <endpoints>localhost:6379</endpoints> </captchaPersistence> </botdetect>
In botdetect.xml
configuration file, we tell BotDetect to use Redis as the BotDetect persistence provider instead of the default one
(SQLite Database). You can find the detailed explanation about this at
Captcha Redis persistence provider documentation.
[back to the top of redis database in .netcore section]
..............................................................
Legacy ASP.NET on Legacy .NET with Redis Session Storage
BotDetect legacy ASP.NET Captcha Simple API uses StackExchange.Redis as Redis ASP.NET client, so you need to ensure StackExchange.Redis NuGet package was installed.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>BotDetect ASP.NET CAPTCHA Options: Application Config Settings Code Example</title> <script type="text/javascript" </head> <body> <form runat="server" class="column" id="form1"> <h1>BotDetect ASP.NET CAPTCHA Options: <br /> Application Config Settings Code Example</h1> <fieldset> <legend>ASP.NET WebForm CAPTCHA Validation</legend> <p class="prompt"> <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label</p> <BotDetect:WebFormsSimpleCaptcha runat="server" ID="RedisCaptchaExample"/> <div class="validationDiv"> <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox> <asp:Button ID="ValidateCaptchaButton" runat="server" /> <asp:Label ID="CaptchaCorrectLabel" runat="server" CssClass="correct"></asp:Label> <asp:Label ID="CaptchaIncorrectLabel" runat="server" CssClass="incorrect"></asp:Label> </div> </fieldset> </form> </body>
Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_PreRender(object sender, EventArgs e) { // initial page setup if (!IsPostBack) { // set control text ValidateCaptchaButton.Text = "Validate"; CaptchaCorrectLabel.Text = "Correct!"; CaptchaIncorrectLabel.Text = "Incorrect!"; // these messages are shown only after validation CaptchaCorrectLabel.Visible = false; CaptchaIncorrectLabel.Visible = false; } if (IsPostBack) { // validate the Captcha to check we're not dealing with a bot bool isHuman = RedisCaptchaExample.Validate(); if (isHuman) { CaptchaCorrectLabel.Visible = true; CaptchaIncorrectLabel.Visible = false; } else { CaptchaCorrectLabel.Visible = false; CaptchaIncorrectLabel.Visible = true; } } } }
Web.config
<?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/> <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/> </appSettings> <system.web> <httpHandlers> <!-- Register the HttpHandler used for BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> <pages controlRenderingCompatibilityVersion="4.5" enableSessionState="true"> <controls> <!-- Register the BotDetect tag prefix for easier use in all pages --> <add assembly="BotDetect" namespace="BotDetect.Web.UI" tagPrefix="BotDetect"/> </controls> </pages> <compilation debug="false" targetFramework="4.5"/> <httpRuntime requestValidationMode="4.5" targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4. 0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> <machineKey compatibilityMode="Framework45"/> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- Register the HttpHandler used for BotDetect Simple API requests (IIS 7.0+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer> </configuration>
botdetect.xml
<?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>RedisCaptchaExample</name> <userInputID>CaptchaCodeTextBox</userInputID> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>Redis</persistenceType> <endpoints>localhost:6379</endpoints> </captchaPersistence> </botdetect>
In botdetect.xml
configuration file, we tell BotDetect to use Redis as the BotDetect persistence provider instead of the default one
(SQLite Database). You can find the detailed explanation about this at Captcha Redis persistence provider documentation.
[back to the top of redis database in legacy .net section]
..............................................................
Java with Redis Session Storage
The Java Simple Captcha options: Server side persistence in Redis database code example shows how to use Redis to store persist Captcha data instead of using default BotDetect HyperSQL Database persistence provider.
As you may know Redis is an open source, in-memory data structure store used to improve data performance. Therefore Captcha data storage via Redis is necessary in real world. This combination makes your application have better performance.
To use Redis to store persist Captcha data, BotDetect Java Simple Captcha provides you a simple way by declaring some Redis configuration info in WEB-INF/botdetect.xml
file, such as: redis host, port, password, ssl.
BotDetect Java Simple Captcha uses Jedis as Redis java client, so you need to ensure Jedis jar library is in the classpath.
Running Example
This example's war file (in BotDetect download package) has already embedded all dependencies.
In case you are making this example from scratch in your IDE, you need to be sure that botdetect.jar
, botdetect-servlet.jar
, jedis.jar
, commons-pool2.jar
are in the classpath.
index.jsp
<%@page import="com.captcha.botdetect.web.servlet.SimpleCaptcha"%> <%@page trimDirectiveWhitespaces="true"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>BotDetect Java Simple CAPTCHA Options: Server Side Persistence in Redis Database Code Example</title> <link type="text/css" rel="stylesheet" href="stylesheet.css" /> </head> <body> <form method="post" action="" class="column" id="form1"> <h1>BotDetect Java Simple CAPTCHA Options: <br /> Server Side Persistence in Redis Database Code Example</h1> <fieldset> <legend>Java CAPTCHA validation</legend> <label for="captchaCode">Retype the characters from the picture:</label> <% // Adding BotDetect Captcha to the page SimpleCaptcha captcha = SimpleCaptcha.load(request, "redisCaptchaExample"); String captchaHtml = captcha.getHtml(); out.write(captchaHtml); %> <div class="validationDiv"> <input name="captchaCode" type="text" id="captchaCode" /> <input type="submit" name="ValidateCaptchaButton" id="validateCaptchaButton" value="Validate" /> <% // when the form is submitted if ("POST".equalsIgnoreCase(request.getMethod())) { // validate the Captcha to check we're not dealing with a bot boolean isHuman = captcha.validate(request.getParameter("captchaCode")); if (isHuman) { // Captcha validation passed, perform protected action out.print("<span class=\"correct\">Correct code</span>"); } else { // Captcha validation failed, show error message out.print("<span class=\"incorrect\">Incorrect code</span>"); } } %> </div> </fieldset> </form> </body> </html>
botdetect.xml
<?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>redisCaptchaExample</name> <userInputID>captchaCode</userInputID> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>REDIS</persistenceType> <host>localhost</host> <port>6379</port> <connectionTimeout>2000</connectionTimeout> <password></password> <ssl>false</ssl> </captchaPersistence> </botdetect>
In WEB-INF/botdetect.xml
configuration file, we tell BotDetect to use Redis as the BotDetect persistence provider instead of the default one
(HyperSQL Database). You can find the detailed explanation about this at Captcha Redis persistence provider documentation.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <session-config> <session-timeout> 30 </session-timeout> </session-config> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
The example WEB-INF/web.xml
file we register SimpleCaptchaServlet
used for BotDetect Captcha requests..
..............................................................
PHP with Redis Session Storage
The BotDetect PHP Simple Captcha options: Server side persistence in Redis database code example shows how to use Redis to store persist Captcha data instead of using default BotDetect Sqlite Database persistence provider.
As you may know Redis is an open source, in-memory data structure store used to improve data performance. Therefore Captcha data storage via Redis is necessary in real world. This combination makes your application have better performance.
To use Redis to store persist Captcha data, BotDetect PHP Simple Captcha provides you a simple way by declaring some Redis configuration info in lib/config/botdetect.xml
file, such as: redis host, port, password, etc.
BotDetect PHP Simple Captcha uses Predis as Redis PHP client, which is already included in our library. You also need to ensure that the Redis server is running.
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>RedisCaptchaExample</name> <userInputID>CaptchaCode</userInputID> <codeLength>3-5</codeLength> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>Redis</persistenceType> <host>localhost</host> <port>6379</port> <timeout>2000</timeout> <password></password> </captchaPersistence> </botdetect>
In lib/botdetect.xml
configuration file, we tell BotDetect to use Redis as the BotDetect persistence provider instead of the default one
(SQLite Database). You can find the detailed explanation about this at
Captcha Redis persistence provider documentation.
index.php
<?php require("lib/simple-botdetect.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>BotDetect PHP CAPTCHA Options: Server Side Persistence in Redis Database Code Example</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link type="text/css" rel="Stylesheet" href="stylesheet.css" /> </head> <body> <form method="post" action="" class="column" id="form1"> <h1>BotDetect PHP CAPTCHA Options: <br /> Server Side Persistence in Redis Database Code Example</h1> <fieldset> <legend>PHP CAPTCHA validation</legend> <label for="CaptchaCode">Retype the characters from the picture:</label> <?php // Adding BotDetect Captcha to the page $RedisCaptchaExample = new SimpleCaptcha("RedisCaptchaExample"); echo $RedisCaptchaExample->Html(); ?> <div class="validationDiv"> <input name="CaptchaCode" type="text" id="CaptchaCode" /> <input type="submit" name="ValidateCaptchaButton" value="Validate" id="ValidateCaptchaButton" /> <?php // when the form is submitted if ($_POST) { // validate the Captcha to check we're not dealing with a bot $isHuman = $RedisCaptchaExample->Validate(); if (!$isHuman) { // Captcha validation failed, show error message echo "<span class=\"incorrect\">Incorrect code</span>"; } else { // Captcha validation passed, perform protected action echo "<span class=\"correct\">Correct code</span>"; } } ?> </div> </fieldset> </form> </body> </html>
..............................................................
ASP.NET Core on .NET Core with Memcached Session Storage
BotDetect ASP.NET Core Captcha Simple API uses EnyimMemcachedCore as Memcached ASP.NET client, so you need to ensure EnyimMemcachedCore NuGet package was installed.
- Views\Example\Index.cshtml
- Controllers\ExampleController.cs
- Startup.cs
- appsettings.json
- botdetect.xml
Views\Example\Index.cshtml
@model CaptchaServerSidePersistenceInMemcachedExample.Models.ExampleModel @section header { <environment names="Development,Staging,Production"> <link rel="stylesheet" href="~/css/StyleSheet.css" /> </environment> } @{ ViewData["Title"] = "BotDetect ASP.NET MVC 6 CAPTCHA Options: Server Side Persistence in Memcached Database Code Example"; } <h2>@ViewData["Title"].</h2> <h3>@ViewData["Message"]</h3> <div class="column"> <h1> BotDetect ASP.NET CAPTCHA Validation: <br /> ASP.NET MVC 6 Web Application CAPTCHA Server Side Persistence in Memcached Database Code Example </h1> <form asp-controller="Example" asp-action="Index" method="post"> <fieldset> <legend>ASP.NET MVC 6 CAPTCHA Validation</legend> <div> <label asp-for="CaptchaCode">Retype the code from the picture:</label> <simple-captcha stylename="ExampleCaptcha" /> <div class="actions"> <input asp-for="CaptchaCode" /> <input type="submit" value="Validate" /> <span asp-validation-for="CaptchaCode"></span> @if ((Context.Request.Method.ToUpper() == "POST") && ViewData.ModelState.IsValid) { <span class="correct">Correct!</span> } </div> </div> </fieldset> </form> </div>
Controllers\ExampleController.cs
using CaptchaServerSidePersistenceInMemcachedExample.Models; using BotDetect.Web.Mvc; using Microsoft.AspNetCore.Mvc; namespace CaptchaServerSidePersistenceInMemcachedExample.Controllers { public class ExampleController : Controller { public IActionResult Index() { return View(); } [HttpPost] [SimpleCaptchaValidation("CaptchaCode", "ExampleCaptcha", "Incorrect!")] public IActionResult Index(ExampleModel model) { return View(model); } public IActionResult Error() { return View(); } } }
appsettings.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } }, "BotDetect": { "CaptchaEndpointPath": "simple-captcha-endpoint.ashx" } }
Register simple-captcha-endpoint.ashx
used for BotDetect Captcha requests.
botdetect.xml
<?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-<!--CONTENTHOOK-BEGIN:string-->BD4_NET_TC<!--CONTENTHOOK-END-->.xsd"> <captchaStyles> <captchaStyle> <name>ExampleCaptcha</name> <userInputID>CaptchaCode</userInputID> <codeLength>3</codeLength> <helpLinkMode>Image</helpLinkMode> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>Memcached</persistenceType> <address>127.0.0.1:11211</address> </captchaPersistence> </botdetect>
In botdetect.xml
configuration file, we tell BotDetect to use Memcched as the BotDetect persistence provider instead of the default one
(SQLite Database). You can find the detailed explanation about this at
Captcha Redis persistence provider documentation.
[back to the top of memcached database in .netcore section]
..............................................................
Legacy ASP.NET on Legacy .NET with Memcached Session Storage
BotDetect legacy ASP.NET Captcha Simple API uses EnyimMemcached as Memcached asp.net client, so you need to ensure EnyimMemcached NuGet package was installed.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>BotDetect ASP.NET CAPTCHA Options: Application Config Settings Code Example</title> <script type="text/javascript" </head> <body> <form runat="server" class="column" id="form1"> <h1>BotDetect ASP.NET CAPTCHA Options: <br /> Application Config Settings Code Example</h1> <fieldset> <legend>ASP.NET WebForm CAPTCHA Validation</legend> <p class="prompt"> <label for="CaptchaCodeTextBox">Retype the characters from the picture:</label</p> <BotDetect:WebFormsSimpleCaptcha runat="server" ID="MemcachedCaptchaExample"/> <div class="validationDiv"> <asp:TextBox ID="CaptchaCodeTextBox" runat="server"></asp:TextBox> <asp:Button ID="ValidateCaptchaButton" runat="server" /> <asp:Label ID="CaptchaCorrectLabel" runat="server" CssClass="correct"></asp:Label> <asp:Label ID="CaptchaIncorrectLabel" runat="server" CssClass="incorrect"></asp:Label> </div> </fieldset> </form> </body>
Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_PreRender(object sender, EventArgs e) { // initial page setup if (!IsPostBack) { // set control text ValidateCaptchaButton.Text = "Validate"; CaptchaCorrectLabel.Text = "Correct!"; CaptchaIncorrectLabel.Text = "Incorrect!"; // these messages are shown only after validation CaptchaCorrectLabel.Visible = false; CaptchaIncorrectLabel.Visible = false; } if (IsPostBack) { // validate the Captcha to check we're not dealing with a bot bool isHuman = MemcachedCaptchaExample.Validate(); if (isHuman) { CaptchaCorrectLabel.Visible = true; CaptchaIncorrectLabel.Visible = false; } else { CaptchaCorrectLabel.Visible = false; CaptchaIncorrectLabel.Visible = true; } } } }
Web.config
<?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/> <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/> </appSettings> <system.web> <httpHandlers> <!-- Register the HttpHandler used for BotDetect Simple API requests --> <add verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </httpHandlers> <pages controlRenderingCompatibilityVersion="4.5" enableSessionState="true"> <controls> <!-- Register the BotDetect tag prefix for easier use in all pages --> <add assembly="BotDetect" namespace="BotDetect.Web.UI" tagPrefix="BotDetect"/> </controls> </pages> <compilation debug="false" targetFramework="4.5"/> <httpRuntime requestValidationMode="4.5" targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4. 0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> <machineKey compatibilityMode="Framework45"/> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <!-- Register the HttpHandler used for BotDetect Simple API requests (IIS 7.0+) --> <remove name="BotDetectCaptchaHandler"/> <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="simple-captcha-endpoint.ashx" type="BotDetect.Web.SimpleCaptchaHandler, BotDetect"/> </handlers> </system.webServer> </configuration>
botdetect.xml
<?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>MemcachedCaptchaExample</name> <userInputID>CaptchaCodeTextBox</userInputID> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>Memcached</persistenceType> <address>127.0.0.1:11211</address> </captchaPersistence> </botdetect>
In botdetect.xml
configuration file, we tell BotDetect to use Memcached as the BotDetect persistence provider instead of the default one
(SQLite Database). You can find the detailed explanation about this at
Captcha Memcached persistence provider documentation.
[back to the top of memcached database in legacy .net section]
..............................................................
Java Memcached with Memcached Session Storage
The Java Simple Captcha options: Server side persistence in Memcached database code example shows how to use Memcached to store persist Captcha data instead of using default BotDetect HyperSQL Database persistence provider.
As you may know Memcached is an open source, in-memory data structure store used to improve data performance. Therefore Captcha data storage via Memcached is necessary in real world. This combination makes your application have better performance.
To use Memcached to store persist Captcha data, BotDetect Java Simple Captcha provides you a simple way by declaring Memcached configuration info in WEB-INF/botdetect.xml
file, such as: memcached host, port.
BotDetect Java Simple Captcha uses Spymemcached as Memcached java client, so you need to ensure Spymemcached jar library is in the classpath.
Running Example
This example's war file (in BotDetect download package) has already embedded all dependencies.
In case you are making this example from scratch in your IDE, you need to be sure that botdetect.jar
, botdetect-servlet.jar
, and spymemcached.jar
are in the classpath.
index.jsp
<%@page import="com.captcha.botdetect.web.servlet.SimpleCaptcha"%> <%@page trimDirectiveWhitespaces="true"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>BotDetect Java Simple CAPTCHA Options: Server Side Persistence in Memcached Database Code Example</title> <link type="text/css" rel="stylesheet" href="stylesheet.css" /> </head> <body> <form method="post" action="" class="column" id="form1"> <h1>BotDetect Java Simple CAPTCHA Options: <br /> Server Side Persistence in Memcached Database Code Example</h1> <fieldset> <legend>Java CAPTCHA validation</legend> <label for="captchaCode">Retype the characters from the picture:</label> <% // Adding BotDetect Captcha to the page SimpleCaptcha captcha = SimpleCaptcha.load(request, "memcachedCaptchaExample"); String captchaHtml = captcha.getHtml(); out.write(captchaHtml); %> <div class="validationDiv"> <input name="captchaCode" type="text" id="captchaCode" /> <input type="submit" name="ValidateCaptchaButton" id="validateCaptchaButton" value="Validate" /> <% // when the form is submitted if ("POST".equalsIgnoreCase(request.getMethod())) { // validate the Captcha to check we're not dealing with a bot boolean isHuman = captcha.validate(request.getParameter("captchaCode")); if (isHuman) { // Captcha validation passed, perform protected action out.print("<span class=\"correct\">Correct code</span>"); } else { // Captcha validation failed, show error message out.print("<span class=\"incorrect\">Incorrect code</span>"); } } %> </div> </fieldset> </form> </body> </html>
botdetect.xml
<?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>memcachedCaptchaExample</name> <userInputID>captchaCode</userInputID> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>MEMCACHED</persistenceType> <address>127.0.0.1:11211</address> </captchaPersistence> </botdetect>
In WEB-INF/botdetect.xml
configuration file, we tell BotDetect to use Memcached as the BotDetect persistence provider instead of the default one
(HyperSQL Database). You can find the detailed explanation about this at
Captcha Memcached persistence provider documentation.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <session-config> <session-timeout> 30 </session-timeout> </session-config> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
The example WEB-INF/web.xml
file we register SimpleCaptchaServlet
used for BotDetect Captcha requests.
..............................................................
PHP Memcached with Memcached Session Storage
The BotDetect PHP Simple Captcha options: Server side persistence in Memcached database code example shows how to use Memcached to store persist Captcha data instead of using default BotDetect Sqlite Database persistence provider.
As you may know Memcached is an open source, in-memory data structure store used to improve data performance. Therefore Captcha data storage via Memcached is necessary in real world. This combination makes your application have better performance.
To use Memcached to store persist Captcha data, BotDetect Php Simple Captcha provides you a simple way by declaring Memcached configuration info in lib/config/botdetect.xml
file, such as: memcached host, port.
BotDetect PHP Simple Captcha uses Memcached as Memcached php client, so you need to ensure Memcached is installed.
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>MemcachedCaptchaExample</name> <userInputID>CaptchaCode</userInputID> <codeLength>3-5</codeLength> </captchaStyle> </captchaStyles> <captchaPersistence> <persistenceType>Memcached</persistenceType> <address>127.0.0.1:11211</address> </captchaPersistence> </botdetect>
In config/botdetect.xml
configuration file, we tell BotDetect to use Memcached as the BotDetect persistence provider instead of the default one
(SQLite Database). You can find the detailed explanation about this at
Captcha Memcached persistence provider documentation.
index.php
<?php require("lib/simple-botdetect.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>BotDetect PHP CAPTCHA Options: Server Side Persistence in Memcached Database Code Example</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link type="text/css" rel="Stylesheet" href="stylesheet.css" /> </head> <body> <form method="post" action="" class="column" id="form1"> <h1>BotDetect PHP CAPTCHA Options: <br /> Server Side Persistence in Memcached Database Code Example</h1> <fieldset> <legend>PHP CAPTCHA validation</legend> <label for="CaptchaCode">Retype the characters from the picture:</label> <?php if (class_exists('Memcached')) { // Adding BotDetect Captcha to the page $MemcachedCaptchaExample = new SimpleCaptcha("MemcachedCaptchaExample"); echo $MemcachedCaptchaExample->Html(); ?> <div class="validationDiv"> <input name="CaptchaCode" type="text" id="CaptchaCode" /> <input type="submit" name="ValidateCaptchaButton" value="Validate" id="ValidateCaptchaButton" /> <?php // when the form is submitted if ($_POST) { // validate the Captcha to check we're not dealing with a bot $isHuman = $MemcachedCaptchaExample->Validate(); if (!$isHuman) { // Captcha validation failed, show error message echo "<span class=\"incorrect\">Incorrect code</span>"; } else { // Captcha validation passed, perform protected action echo "<span class=\"correct\">Correct code</span>"; } } ?> </div> <?php } else { echo "<div class='note warning'>Class Not Found: Memcached. You need to install Memcached first</div>"; } ?> </fieldset> </form> </body> </html>
Please Note
This document is not up to date. We are working on fixing it. Your Simple API integration efforts should start with one of the following four step-by-step integration guides: Angular Captcha, AngularJS Captcha, jQuery Captcha, React Captcha.
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