BotDetect CAPTCHA ASP.NET FAQ
I. Installation & Deployment
- Can I use the BotDetect CAPTCHA with ASP.NET 2.0?
- Can I use the BotDetect CAPTCHA with .NET framework 3.0 or 3.5?
- Can I use the BotDetect CAPTCHA with Visual Studio 2008?
- Is ASP.NET Session State required for BotDetect CAPTCHA?
- Can I use BotDetect ASP.NET CAPTCHA in a Web Farm / Web Garden?
- Is there any rework involved if I develop my ASP.NET pages using the trial version of BotDetect CAPTCHA and, later on, buy the final version, other than recompiling the code?
- My site is running on ASP.NET 2.0 and my host no longer permits full trust security levels. Does your product run under ASP.NET 2.0 in medium trust?
- Why does the BotDetect CAPTCHA control require being installed as an HttpHandler in the web.config of my ASP.NET project?
- Does BotDetect ASP.NET CAPTCHA work with IIS 7.0? Everything works with IIS 6.0, but when I deploy my project to IIS 7.0, the CAPTCHA image is missing.
II. Implementation
- I am trying to setup a sample project using the BotDetect ASP.NET CAPTCHA functionality, but having trouble getting the CAPTCHA image to display. I notice it's pointing to LanapCaptcha.aspx, however there's no such page inside the product's folder (and subfolders).
- I'm trying to add the BotDetect CAPTCHA control to the login.aspx page, which is presented to the user before he is authenticated. However, the CAPTCHA image fails to display for non-authenticated users. I am using Forms Authentication, so I cannot use your sample web.config file as is.
- I added a reference to your component in my project, but I still get the following compilation error: Could not load file or assembly 'Lanap.BotDetect' or one of its dependencies. The system cannot find the file specified. The Bin folder contains a file called Interop.LANAPBOTDETECTLib.dll, but there is no Lanap.BotDetect.dll.
- We are trying to use the BotDetect CAPTCHA control in an ASP.NET 2.0 AJAX UpdatePanel but it appears the Captcha.Validate method always returns false, even though the end user enters the correct code.
- The audio CAPTCHA seems to always use a different code than the one shown in the CAPTCHA image. This bug only seems to occur for users that have Windows Vista and Internet Explorer 7.0.
- The audio CAPTCHA seems to always use a different code than the one shown in the CAPTCHA image. This bug only seems to occur for Google Chrome users.
- We're trying to use your product with DotNetNuke 4.5.5, and running into some trouble because of an apparent interaction with the URL rewriting HTTP module. CAPTCHA image and sound requests are made using relative paths, which are being mangled by the URL rewriter and never passed to your HttpHandler. Do you have a fix for this?
- We're having issues with a) the CAPTCHA image not displaying b) CAPTCHA validation returning false despite entering the correct code c) the code in the audio CAPTCHA being different than the one drawn in the CAPTCHA image. It seems only AOL users are experiencing these problems.
- We're trying to use BotDetect CAPTCHA on a form that is <iframe>-d into another page that's on a different domain. The CAPTCHA works in Firefox, but not in IE (version 6 or 7). Have you seen this problem before?
- I'm getting the Key cannot be null. Parameter name: key error in the logs a lot. Do you know what might be causing this?
- I am testing the BotDetect CAPTCHA on my ASP.NET site. The issue I am having is that Google Webmaster Tools are reporting a lot of crawl errors for CAPTCHA-related paths. I get a lot of similar errors, all with sliightly different Url's, so I'm not sure I can block them in the robots.txt file.
- I am using CAPTCHA images with a height of only 30 pixels, and the reload icon is shown below the CAPTCHA image - is there a way to make it show to the right of the speaker icon, instead of below it?
- I want to validate the CAPTCHA on the client side without doing a post back. Do you have any suggestions? Is it possible to retrieve the current CAPTCHA code at Page_Load, and send it to the client?
- After adding BotDetect CAPTCHA to my form, I've noticed that the first time I access the page the URL modifies itself, by adding a querystring: ?AspxAutoDetectCookieSupport=1. This querystring disappears on the next request, but I'm wondering is it possible to hide it completely?
- I'm using the latest BotDetect CAPTCHA and the audio sometimes doesn't coincide with the value displayed in the CAPTCHA picture. I have seen the exact same behavior on your demo if I allow 20 minutes or so to pass before pressing the "play audio" button.
- Do you have any sample code on how to use BotDetect CAPTCHA with the ASP.NET CreateUserWizard control?
- I have a form with several fields protected with the BotDetect CAPTCHA, and when the user enters the correct CAPTCHA code but server-side validation of another field fails, they are shown another CAPTCHA image with a different code. Is there a way to show them the same CAPTCHA image and keep the entered code, so they don't have to solve more than one CAPTCHA just because they entered an invalid value for another field?
I. Installation & Deployment
Can I use the BotDetect CAPTCHA with ASP.NET 2.0?
Yes, you can use the BotDetect CAPTCHA control with ASP.NET 2.0.
Both the trial and full versions of the product come with separate ASP.NET 1.1 and ASP.NET 2.0 installations, containing the respective versions of the component and included sample projects appropriate for your .NET framework version.
Can I use the BotDetect CAPTCHA with .NET framework 3.0 or 3.5?
Yes, you can use the BotDetect CAPTCHA control with .NET framework versions 3.0 and 3.5. Just use the BotDetect CAPTCHA ASP.NET 2.0 installation package.
The ASP.NET 2.0 version of BotDetect is compatible with newer versions, since both of those .NET versions are running on the core .NET 2.0 runtime - .NET 3.0 and .NET 3.5 are implemented as library updates for the core .NET 2.0 framework.
Can I use the BotDetect CAPTCHA with Visual Studio 2008?
Yes, the BotDetect CAPTCHA control from the ASP.NET 2.0 installation package will work without any problems when added to Visual Studio 2008 projects.
The sample projects included in the installation will work after you run the Conversion Wizard, which will start automatically when you open them in Visual Studio 2008.
Is ASP.NET Session State required for BotDetect CAPTCHA?
Yes, ASP.NET Session State is a requirement for BotDetect.
Please note that it doesn't have to be the default InProc memory Session State – you can use any Microsoft's or custom Session provider you like (database, state server, file system, etc.).
BotDetect doesn't require a specific mode of persistence (it will work as long as it can save the required data somewhere), but since ASP.NET provides a way to customize the exact mode of persistence and hook it up to the default Session object (as explained at http://msdn2.microsoft.com/en-us/library/aa479034.aspx), all persistence calls in the BotDetect code are made using the Session object.
Can I use BotDetect ASP.NET CAPTCHA in a Web Farm / Web Garden?
Yes. Note that BotDetect CAPTCHA requires Session State persistence, so you will have to enable Session State for your web application. In a Web Farm / Web Garden scenario, this means either:
- Configuring ASP.NET to use the SQL Server or .NET State Server modes of Session State persistence, and keeping the Session State for your whole Web Farm on one server.
- Continue using InProc Session State on each individual server, which means you will have to ensure that clients return to the server containing their existing Session State data on all Http requests after the first one. This is known as enabling sticky connections. Please check your load-balancer settings.
For more information on these topics, consult the following online resources:
Is there any rework involved if I develop my ASP.NET pages using the trial version of BotDetect CAPTCHA and, later on, buy the final version, other than recompiling the code?
There is no rework involved when you purchase the final version of BotDetect ASP.NET CAPTCHA control.
You can develop with the trial version, and after purchasing just replace the Lanap.BotDetect.dll trial assembly on your server with the release version. That way, there is no need for redeveloping or even recompiling.
This is explained in more detail at the BotDetect CAPTCHA trial version information page.
My site is running on ASP.NET 2.0 and my host no longer permits full trust security levels. Does your product run under ASP.NET 2.0 in medium trust?
Yes, since version 2.0, BotDetect runs under ASP.NET 2.0 in medium trust.
In other words, the Lanap.BotDetect.dll assembly has been marked with:
[assembly: System.Security.AllowPartiallyTrustedCallers]
Why does the BotDetect CAPTCHA control require being installed as an HttpHandler in the web.config of my ASP.NET project?
A HttpHandler is needed to generate CAPTCHA images. We do not save those images to the hard drive or reuse them in any way, but generate them on-the-fly for security reasons. An ASP.NET HttpHandler allows us to generate CAPTCHA images which only the current user can see, and which allow only one validation attempt per CAPTCHA code.
Does BotDetect ASP.NET CAPTCHA work with IIS 7.0? Everything works with IIS 6.0, but when I deploy my project to IIS 7.0, the CAPTCHA image is missing.
Yes, BotDetect ASP.NET CAPTCHA works with IIS 7.0. If you are running ASP.NET in integrated mode, you need to add the following declaration to your project's web.config file:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="LanapCaptchaHandler"/>
<add name="LanapCaptchaHandler" preCondition="integratedMode"
verb="*" path="LanapCaptcha.aspx"
type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect" />
</handlers>
</system.webServer>
II. Implementation
I am trying to setup a sample project using the BotDetect ASP.NET CAPTCHA functionality, but having trouble getting the CAPTCHA image to display. I notice it's pointing to LanapCaptcha.aspx, however there's no such page inside the product's folder (and subfolders).
LanapCaptcha.aspx is an HttpHandler declared in the Lanap.BotDetect.dll assembly, and it doesn't exist on your disk drive (like a file). Here is a nice article explaining HttpHandler logic: http://www.devx.com/dotnet/Article/6962/1954?pf=true.
In short: you dont have to look for the LanapCaptcha.aspx file. Simply add the Lanap.BotDetect.dll component reference to your project, and the Captcha control to the web form. Then, open the web.config file and add the HttpHandler declaration to the <system.web> section:
<system.web>
<httpHandlers>
<add verb="*" path="LanapCaptcha.aspx"
type="Lanap.BotDetect.CaptchaHandler,
Lanap.BotDetect"/>
</httpHandlers>
</system.web>
Save all changes, compile and run the project and you will see a CAPTCHA image rendered on your web form. You might also want to check the How To use BotDetect ASP.NET CAPTCHA in Visual Studio 2005 guide, where all required steps are explained in greater detail.
I'm trying to add the BotDetect CAPTCHA control to the login.aspx page, which is presented to the user before he is authenticated. However, the CAPTCHA image fails to display for non-authenticated users. I am using Forms Authentication, so I cannot use your sample web.config file as is.
Here is the section of the config file for authentication:
<authentication mode = "Forms">
<forms name = ".SECAUTH" loginUrl="login.aspx"
timeout="480" />
</authentication>
<authorization>
<deny users="?" />
</authorization>>
You need to disable authentication checks for BotDetect CAPTCHA requests. Adding this code inside the <configuration> section of your web.config will solve the problem:
<location path="LanapCaptcha.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
I added a reference to your component in my project, but I still get the following compilation error:
Could not load file or assembly 'Lanap.BotDetect' or one of its dependencies. The system cannot find the file specified.
The Bin folder contains a file called Interop.LANAPBOTDETECTLib.dll, but there is no Lanap.BotDetect.dll.
If you have both BotDetect CAPTCHA for ASP.NET and BotDetect CAPTCHA for ASP installed, be careful to only use the .NET version in ASP.NET projects.
When you add a reference to the ASP version in a .NET project, Visual Studio automatically generates the COM Interop wrapper (Interop.LANAPBOTDETECTLib.dll), but the resulting component interface is still different and not easily usable from ASP.NET projects.
The .NET version of BotDetect CAPTCHA can be found at
C:\Program Files\Lanapsoft\BotDetect\ASP.NET 2.0\v2.0\ Assembly\Lanap.BotDetect.dll
The COM version of BotDetect CAPTCHA is located at
C:\Program Files\Lanapsoft\BotDetect\ASP\v2.0\Component\ LanapBotDetect.dll
When you remove the Interop.LANAPBOTDETECTLib.dll reference and add the Lanap.BotDetect.dll one, this error will go away.
We are trying to use the BotDetect CAPTCHA control in an ASP.NET 2.0 AJAX UpdatePanel but it appears the Captcha.Validate method always returns false, even though the end user enters the correct code.
UPDATE: This issue has been completely resolved in BotDetect for ASP.NET v2.0.10 (released at 2008-04-06), so you just have to upgrade to the latest version.
The workaround instructions below apply only to BotDetect versions 2.0.6 - 2.0.9, and while still functional, they are considered deprecated.
Older versions workaround (deprecated)
The resolution of this issue requires BotDetect for ASP.NET v2.0.6 (released at 2007-07-02) or newer. If you have an older version, please contact us for the update.
You can see how to make the Captcha control validate inside an UpdatePanel in the special ASP.NET Ajax CAPTCHA sample coming with BotDetect CAPTCHA installations.
Basically, you should use a slightly modified version of the control (called AjaxCaptcha) instead of the regular Lanap.BotDetect.Captcha one. There are only three short steps for migrating from a regular version:
- Copy the AjaxCaptcha.cs (or .vb) file from the sample to the App_Code folder of your website project.
Add:
<%@Register Assembly="App_Code" Namespace=" Lanap.BotDetect" TagPrefix="BotDetect" %>
to the top of the .aspx file, just below the <%@Page> directive.
Replace the <BotDetect:Captcha> control declaration with the <BotDetect:AjaxCaptcha> one, for example:
<BotDetect:Captcha ID="SampleCaptcha" runat="server" />
should become:
<BotDetect:AjaxCaptcha ID="SampleCaptcha" runat="server" SoundEnabled="False" />
Note that the AjaxCaptcha control in the sample has the SoundEnabled property set to false – the partial postback used by the UpdatePanel doesn't mix well with the current versions of Firefox and certain forms of DOM scripting. Because of that, we don't recommend using the audio CAPTCHA inside an Update Panel at the moment.
(UPDATE: This audio CAPTCHA problem was caused by a bug in the Quicktime v7.1.6 plugin for Firefox, and was fixed in later versions of the player. The BotDetect audio CAPTCHA is fully functional inside an ASP.NET Ajax Update Panel.)
When you make these changes, the required hidden field values will be sent on UpdatePanel partial postbacks, and the CAPTCHA validation will work properly.
The audio CAPTCHA seems to always use a different code than the one shown in the CAPTCHA image. This bug only seems to occur for users that have Windows Vista and Internet Explorer 7.0.
The resolution of this issue requires BotDetect for ASP.NET v2.0.7 (released at 2007-07-18) or newer. If you have an older version, please contact us for the update.
Besides uploading the latest .dll to your server(s), you also need to make a small change to the <sessionState> element declaration in your application's web.config file. For example, if you are using a declaration like:
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20" />
Please change it to:
<sessionState mode="InProc" cookieless="AutoDetect"
timeout="20" sessionIDManagerType="
Lanap.BotDetect.Persistence.CustomSessionIDManager,
Lanap.BotDetect" />
After adding the custom sessionIDManagerType value you shouldn't experience this problem anymore.
Explanation
This problem is caused by Windows Media Player 11 (used on Vista), which apparently makes 2 consecutive requests for a single speaker icon click (all the other players - including Windows Media Player 9.0 and 10.0 - only make a single request). The first request actually works properly (the right code is read from the Session state etc.), but the second request comes without the ASP.NET Session cookie, causing a completely new Session (and a new code) to be created.
If you use the updated version of the .dll, and make the change in web.config written about earlier, the Session ID (which is usually persisted in the ASP.NET Session cookie, or in the Url fragment with cookieless Sessions) is also passed as a querystring parameter of the sound request. The custom Session ID Manager is then used to recognize returning users and generate the sound file from correct Session data.
An alternative solution is to always use cookieless Sessions. If you prefer this, please note that all Urls in your application will be changed to include the Session ID, while using the first solution only changes the audio CAPTCHA request Url.
The audio CAPTCHA seems to always use a different code than the one shown in the CAPTCHA image. This bug only seems to occur for Google Chrome users.
To resolve this problem, you need to make a small change to the <sessionState> element declaration in your application's web.config file. For example, if you are using a declaration like:
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20" />
Please change it to:
<sessionState mode="InProc" cookieless="AutoDetect"
timeout="20" sessionIDManagerType="
Lanap.BotDetect.Persistence.CustomSessionIDManager,
Lanap.BotDetect" />
After adding the custom sessionIDManagerType value you shouldn't experience this problem anymore.
Explanation
Our investigation of the issue shows that Chrome forwards the sound CAPTCHA request to Windows Media Player, which for some reason makes the sound request without the ASP.NET Session cookie, causing a completely new Session (and a new code) to be created.
If you make the change in the web.config file, the Session ID (which is usually persisted in the ASP.NET Session cookie, or in the Url fragment with cookieless Sessions) is also passed as a querystring parameter of the sound request. The custom Session ID Manager is then used to recognize returning users and generate the sound file from correct Session data.
An alternative solution is to always use cookieless Sessions. If you prefer this, please note that all Urls in your application will be changed to include the Session ID, while using the first solution only changes the audio CAPTCHA request Url.
We're trying to use your product with DotNetNuke 4.5.5, and running into some trouble because of an apparent interaction with the Url Rewriting HttpModule. CAPTCHA image and sound requests are made using relative paths, which are being mangled by the Url Rewriter and never passed to your HttpHandler. Do you have a fix for this?
This issue can be resolved by excluding BotDetect CAPTCHA image and sound paths in the DotNetNuke Url Rewriter configuration. The only additional step necessary for DotNetNuke users is to add:
<RewriterRule> <LookFor>.*LanapCaptcha.aspx(.*)</LookFor> <SendTo>~/LanapCaptcha.aspx$1</SendTo> </RewriterRule>
to SiteUrls.config in the base DotNetNuke web site directory and BotDetect CAPTCHA will work properly.
We're having issues with a) the CAPTCHA image not displaying b) CAPTCHA validation returning false despite entering the correct code c) the code in the audio CAPTCHA being different than the one drawn in the CAPTCHA image. It seems only AOL users are experiencing these problems.
This issue is specific to multiple load-balanced servers using InProc ASP.NET Session State and sticky connections.
The problem with AOL users is that they are connecting through client proxies, and don't necessarily have the same IP address on subsequent requests. Depending on your load balancer settings, this might cause sticky connections to stop working for them. This causes CAPTCHA image drawing requests to land on the wrong server, without the Session variables they need.
You can find more explanations at:
- In-process Session State + More than One Web Server at http://www.hanselman.com/blog/LoadBalancingAndASPNET.aspx
- Problems with ASP Session State -> Server farm limitations at http://msdn2.microsoft.com/en-us/library/ms972429.aspx
- Normal AOL proxy behavior or DOS attack? at http://groups.google.hr/group/microsoft.public.inetserver.iis.security/
browse_thread/thread/1842b9172aab60e3/17446b9c304253ce?lnk=st&q=AOL+
session+state+ASP.Net&rnum=3&hl=hr#17446b9c304253ce
So the solution would be to:
- Use a single server for Session State persistence on all of your load-balanced servers (using the SQL or StateServer ASP.NET Session State modes).
- Or, you can maybe configure your load balancer to successfully implement sticky connections even for AOL users. For example, the hardware load balancer could add a cookie of its own etc. Please check your load-balancer's FAQ for details.
We're trying to use BotDetect CAPTCHA on a form that is <iframe>-d into another page that's on a different domain. The CAPTCHA works in Firefox, but not in IE (version 6 or 7). Have you seen this problem before?
The CAPTCHA doesn't work in this scenario because ASP.NET Session state is not being persisted properly for the user. The problem appears in IE because of the following:
- On all requests after the first, the user is returned to the appropriate Session state using the ASP.Net Session cookie
- Your Session state cookie is set for Domain #1 (with the form containing the BotDetect CAPTCHA)
- The main page (containing the <iframe>) is located at Domain #2
- Cookies located at different domains than the main page are known as 3rd party cookies; they are a known cause of security issues, and are blocked by default in IE
- When opening your page in IE 7, you can confirm this is really causing the issue by changing your IE settings to allow 3rd party cookies ( Tools > Internet Options > Privacy > Advanced ). When you make this change, the CAPTCHA should start working properly
Solution
You should definitely modify your code not to use cross-domain cookies, since many users will have them blocked by default, and for good reasons.
The simplest solution is to configure your application (the form containing the CAPTCHA) to always use cookieless ASP.NET Sessions - persisting the current SessionID in an Url fragment, instead of a cookie.
You can do this by changing the <sessionState> element declaration in the web.config file (the same one where you registered the BotDetect HttpHandler). For example, if you are using a declaration like:
<sessionState mode="InProc" cookieless="AutoDetect" timeout="20" />
Please change it to:
<sessionState mode="InProc" cookieless="true" timeout="20" />
Note that this will dynamically change the Url of the form containing a BotDetect CAPTCHA to contain the SessionID fragment (something like /(S(vi1maxipelkbz2ahryodzirf))/), but shouldn't affect the Url's of your main page (unless you change that page's web.config file too).
I'm getting the "Key cannot be null. Parameter name: key" error in the logs a lot, with the following stack trace:
at System.Collections.Hashtable.ContainsKey(Object key) at Lanap.BotDetect.CaptchaCodeCollection.GetCode( CodeSetterDelegate codeSetter, String instanceTimestamp, CodeGenerationPurpose purpose, CodeTypeEnum codeType, Int32 codeLength) at Lanap.BotDetect.CaptchaHandler.DrawImage(HttpContext context)
Do you know what might be causing this?
The only occasion when we get errors like these are when the client makes a particular kind of an invalid CAPTCHA image or sound request. This usually happens only with bots trying to access the page.
In particular, if your server logs show this error happens with the User Agent string similar to Mozilla/3.01 (compatible;), or the querystring of the image request is something like get=image&c=default_ctl00_contentplaceholdermain_captcha1 &t=3172526 2 - with the & entities instead of &, you can be sure it's some kind of bot. All modern browsers resolve XHMTL entities properly, so human users shouldn't be having any problems with this.
We've added fixes for this in BotDetect for ASP.NET v2.0.8 (unescaped & entities in requests) and v2.0.10 (requests conatining &amp;amp;-type constructs), so these invalid CAPTCHA requests don't result in any exceptions being thrown and logged. If you have an older version, please contact us for the update.
I am testing the BotDetect CAPTCHA on my ASP.NET site. The issue I am having is that Google Webmaster Tools are reporting a lot of crawl errors for CAPTCHA-related paths. For example, errors occur for requests of the following type:
www.xyz.com/(S(0v2gv2zl0nf1pd45y3k4itbx))/LanapCaptcha.aspx ?get=image&c=default_samplecaptcha &t=07855def910d4a8b8256975264967547 &s=0v2gv2zl0nf1pd45y3k4itbx
I get a lot of similar errors, all with sliightly different Url's, so I'm not sure I can block them in the robots.txt file.
BotDetect CAPTCHA request paths should definitely be blocked in the robots.txt file.
There is a number of slightly different Url's reported since Googlebot crawls the pages without cookies, and the ASP.NET Cookieless Url's change on every visit (they are rewritten to contain the Session ID).
Here is how you can block such requests in the robots.txt file:
User-Agent: Googlebot Disallow: /*/LanapCaptcha.aspx Disallow: /*/WebResource.axd # other googlebot restrictions go below /forbidden.html # ... User-Agent: * # other restrictions go below /forbidden.html # ...
Since the Url's of those requests change dynamically, they can be blocked from Googlebot by a specific robots.txt extension implemented by Google (the wildcard character). However, other crawlers might not understand the wildcard character, so this declaration needs to be in the Googlebot-specific part of the robots.txt file.
Also, note that generally forbidden files (as shown on the example forbidden.html file) need to be declared twice: in both the Googlebot and the general sections of the robots.txt file. Unfortunatelly, this is how the robots.txt standard works - Googlebot will only read the User-Agent: Googlebot section, and then ignore the User-Agent: * declarations.
I am using CAPTCHA images with a height of only 30 pixels, and the reload icon is shown below the CAPTCHA image - is there a way to make it show to the right of the speaker icon, instead of below it?
You can make the Reload button render to the right of the speaker icon by adding the following declarations to the CSS stylesheet of the CAPTCHA-protected page:
#LBD_CaptchaDiv{
width: 310px !important;
}
#LBD_CaptchaDiv #LBD_CaptchaIcons {
width: 55px !important;
height: 25px;
}
#LBD_CaptchaDiv #LBD_CaptchaIcons img {
padding-right: 4px !important;
}
If the CAPTCHA image has a height different than 250 pixels, change the first declaration according to the following formula:
<#LBD_CaptchaDiv width> = <CAPTCHA image width> + 60 px.
This will display the icons in a horizontal layout, as shown in the screenshot above.
I want to validate the CAPTCHA on the client side without doing a post back. Do you have any suggestions? Is it possible to retrieve the current CAPTCHA code at Page_Load, and send it to the client?
If you want to avoid full page postbacks, you could take a look at the BotDetect CAPTCHA Ajax Demo coming with the installation, which uses an ASP.NET Ajax UpdatePanel to only post and reload the part of the page with the CAPTCHA challenge.
Pure client-side CAPTCHA validation drawbacks
Pure client-side CAPTCHA validation (without any communication with the server) is not supported by BotDetect, since such a CAPTCHA is trivial to bypass, and doesn't provide any serious protection from bots. For example:
- You want users to post comments only if they have successfully solved the CAPTCHA.
- If the CAPTCHA validation is purely client-side, this means JavaScript code must send the user's comment to the server when the CAPTCHA code is entered correctly.
- So the spammer only needs to solve the CAPTCHA once, and note how you handle the result: e.g. sending a specific POST parameter, or redirecting to a specific page.
- After that, they can simulate the same behavior in their bot and bypass the CAPTCHA completely - by simply faking the POST parameter, or accessing the redirection landing page directly.
- You can back the client-side CAPTCHA validation by also validating the same user input on the server once the page is posted and before recording the user comment.
- But since you are keeping the correct CAPTCHA solution on the client for validation, bots can have easy access to that code and then always solve the CAPTCHA correctly.
The exact details depend on your specific use-case and CAPTCHA integration scenario. But essentially, all client-side code is insecure and can be faked or modified by malicious parties. As a consequence, the CAPTCHA codes must only be kept on the server, and all CAPTCHA validation must be performed on the server as well.
Client-side CAPTCHA validation - the solution
You can avoid full page postbacks by using ASP.NET Ajax or another Ajax library to make asynchronous CAPTCHA validation requests to the server, and processing the result on the client:
- When the Ajax CAPTCHA validation fails, you can show the user a new CAPTCHA image without affecting the rest of the page, thus improving the user experience and overall usability of the page.
- You should always change the CAPTCHA code in such cases, since allowing multiple attempts at solving the same CAPTCHA makes OCR guessing much easier.
- When the Ajax CAPTCHA validation succeeds, you should then submit the page to the server and validate the user CAPTCHA input again.
- Only after successful server-side CAPTCHA validation should you execute the "protected" operation (e.g. record the user comment) on the server.
After adding BotDetect CAPTCHA to my form, I've noticed that the first time I access the page the URL modifies itself, by adding a querystring: ?AspxAutoDetectCookieSupport=1. This querystring disappears on the next request, but I'm wondering is it possible to hide it completely?
The AspxAutoDetectCookieSupport=1 querystring is added automatically by ASP.NET during the cookie support detection phase. Since <sessionState> cookieless attribute in the web.config file is set to "AutoDetect", the ASP.NET runtime tries to detect whether the user's browser supports cookies, and the querystring parameter is added during that process. If cookies are supported, the Session ID is kept in a cookie, and if not the Session ID is sent in the Url of all future requests by that user.
The only way to remove the querystring is to set the cookieless attribute to either "true" or "false" in your web.config file. But in that case, all Urls will be dynamically changed to include the ASP.NET Session identifier (cookieless="true"), or CAPTCHA validation will always fail for users who have cookies disabled in their browser (cookieless="false").
Since this is built-in ASP.NET behavior, you will have to decide which cookieless value best suits your application. You can read more about cookieless Sessions at http://msdn.microsoft.com/en-us/library/aa479314.aspx.
I'm using the latest BotDetect CAPTCHA and the audio sometimes doesn't coincide with the value displayed in the CAPTCHA picture. I have seen the exact same behavior on your demo if I allow 20 minutes or so to pass before pressing the "play audio" button.
The behavior of our online demo is related to the ASP.NET Session timeout - since the CAPTCHA codes are kept in ASP.NET Session state, and our online demo uses the default Session state timeout of 20 minutes, this behavior is more or less by design.
If your page requires that the CAPTCHA codes remain valid for longer periods of time, you could:
- Increase the Session timeout by changing the timeout attribute of the <sessionState> element in your project's web.config file. However, this will increase the IIS memory consumption because the Session data will be kept longer for every connecting client. And if some users stay on your page even longer than the timeout you set, they will still experience this problem.
- A better solution would be to keep the Session timeout low (20 minutes), and have a "heartbeat" client script which prolongs the Session for users who stay on the page longer. For example, since the default timeout is 20 minutes, the Javascript code could make an asynchronous (Ajax) request to your application every 15 minutes, keeping the Session alive if users open the page and remain inactive for longer periods of time.
If the audio CAPTCHA in your project is different than the code rendered in the image even when you don't wait for the Session to timeout, you should investigate other settings. For example, if you are using InProc ASP.NET Session state, the data can still be lost even with a heartbeat script keeping users active if the IIS worker process gets recycled. Or, if you have more than one instance of the worker process on the same server (a web garden), different worker processes will have separate Session states.
In such cases you should switch your project to either StateServer or SQLServer ASP.NET Session state modes, which are not dependent on the IIS worker process lifecycle.
Do you have any sample code on how to use BotDetect CAPTCHA with the ASP.NET CreateUserWizard control?
Here's an example of how validating BotDetect CAPTCHA user input inside CreateUserWizard controls might be accomplished.
Form .aspx code
Let's assume you have the following CreateUserWizard declaration in your .aspx file:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnNextButtonClick="CreateUserWizard1_NextButtonClick">
and that you modified the
<WizardSteps>
<asp:CreateUserWizardStep runat="server">
<ContentTemplate>
to include the following Captcha:
<BotDetect:Captcha ID="Captcha1" runat="server" /> <asp:TextBox ID="CodeTextBox" runat="server"></asp:TextBox> <asp:Label ID="CodeIncorrectLabel" runat="server" Text="Incorrect code!" Visible="false"></asp:Label>
Form code-behind
You can add Captcha validation in your code-behind file with the following code in the NextButtonClick handler:
[C#]
protected void CreateUserWizard1_NextButtonClick(object sender,
WizardNavigationEventArgs e)
{
if (e.CurrentStepIndex == 0)
{
Captcha Captcha1 = (Captcha) CreateUserWizard1.
CreateUserStep.ContentTemplateContainer.
FindControl("Captcha1");
TextBox CodeTextBox = (TextBox) CreateUserWizard1.
CreateUserStep.ContentTemplateContainer.
FindControl("CodeTextBox");
Label CodeIncorrectLabel = (Label) CreateUserWizard1.
CreateUserStep.ContentTemplateContainer.
FindControl("CodeIncorrectLabel");
string userInput = CodeTextBox.Text;
if (!Captcha1.Validate(userInput))
{
CodeIncorrectLabel.Visible = true;
e.Cancel = true;
}
else
{
CodeIncorrectLabel.Visible = false;
e.Cancel = false;
}
}
}
[VB.Net]
Protected Sub CreateUserWizard1_NextButtonClick(ByVal sender
As Object, ByVal e As WizardNavigationEventArgs)
If e.CurrentStepIndex = 0 Then
Dim Captcha1 As Lanap.BotDetect.Captcha = _
CType(CreateUserWizard1.CreateUserStep. _
ContentTemplateContainer.FindControl("Captcha1"), _
Lanap.BotDetect.Captcha)
Dim CodeTextBox As TextBox = _
CType(CreateUserWizard1.CreateUserStep. _
ContentTemplateContainer.FindControl("CodeTextBox"), _
TextBox)
Dim CodeIncorrectLabel As Label = _
CType(CreateUserWizard1.CreateUserStep.
ContentTemplateContainer.FindControl( _
"CodeIncorrectLabel"), Label)
Dim userInput As String = CodeTextBox.Text
If (Not Captcha1.Validate(userInput)) Then
CodeIncorrectLabel.Visible = True
e.Cancel = True
Else
CodeIncorrectLabel.Visible = False
e.Cancel = False
End If
End If
End Sub
I have a form with several fields protected with the BotDetect CAPTCHA, and when the user enters the correct CAPTCHA code but server-side validation of another field fails, they are shown another CAPTCHA image with a different code. Is there a way to show them the same CAPTCHA image and keep the entered code, so they don't have to solve more than one CAPTCHA just because they entered an invalid value for another field?
If the users enters a correct CAPTCHA code but for example username validation fails, they definitely should not have to solve another CAPTCHA. The purpose of CAPTCHA is to ensure the user is human, and when they solve it successfully the first time they have passed this test.
If you have to return them to the form because another field value needs to be corrected, it's best not to show them a CAPTCHA at all, since it's purpose has been fulfilled. The simplest way to remember that the user has solved the CAPTCHA successfully is to store the result on the server-side, for example:
bool isHuman = SampleCaptcha.Validate(userInput);
Session["IsHuman"] = isHuman;
if (Page.IsValid && isHuman)
{
// the protected code, e.g. account registration or comment post
}
Then, the stored value is checked before displaying the CAPTCHA to the user, and the CAPTCHA is only displayed if it hasn't already been solved:
protected void Page_PreRender(object sender, EventArgs e)
{
bool isHuman = false;
if (null != Session["IsHuman"])
{
try
{
isHuman = (bool) Session["IsHuman"];
}
catch { // ignore errors }
}
// don't show the CAPTCHA if already solved
if (isHuman)
{
SampleCaptcha.Visible = false;
CodeTextBox.Visible = false;
}
}
For security reasons, it is not possible to get the same BotDetect CAPTCHA image on two page loads, nor to use the same code for more than one CAPTCHA image.


