What are we facing?
Perhaps the most common use for dynamic web pages is the retrieval of information from users, this retrieval is made using web forms. A common problem faced by the web developers is the existence of automated scripts that submit forms automatically mainly to send spam or try to saturate the server with more requests than it can handle. To avoid this kind of problems, the sites need a way to ensure that the form is being submitted by a person, not a computer program.
A CAPTCHA is a "type of challenge-response test used to ensure that the response is not generated by a computer"1, the most common type of challenge consists of an image with letters and/or numbers, often with a distorted background or with external symbols or lines, easy to recognize for a human but very difficult for a program, even with OCR capabilities.
There are many companies that offer components to add a CAPTCHA to your form, for this article we will see how to use the reCAPTCHA implementation, this is the implementation recommended by the CAPTCHA creators.
The Solution
The use of reCAPTCHA is really easy, and there are implementations for most programming environments. To add it to an ASP.Net Web Form, we need to follow these steps:
- Download the free component from the official reCAPTCHA page
- Register in the page to get the keys needed to generate and validate the CAPTCHA (In order to use the free service you will need to specify the domain where your page with the CAPTCHA will be hosted).
- Create our form with the information we need to retrieve.
- Add to your site a reference to the dll that comes with the library code (In the downloaded file, in the path
recaptcha-dotnet\library\bin\Release\Recaptcha.dll).
- Register the recaptcha component in your .aspx page
( <% @ Register TagPrefix ="recaptcha" Namespace ="Recaptcha" Assembly ="Recaptcha" %> )
- Add the captcha control to the form, setting the values for the public and private keys (obtained in step 2).
<recaptcha:RecaptchaControl
ID="recaptcha"
runat="server"
PublicKey=""
PrivateKey=""
/>
After this, the CAPTCHA should be working, now you only have to validate that the entered value is correct.
- Validate the entered value in server side by calling the ASP.Net property
Page.IsValid, if it returns true, then the value in the CAPTCHA is right, otherwise you should
display a validation error.
After this, your form will have a CAPTCHA field that will look like this one
(taken from the reCAPTCHA site)
With this you'll add a very simple (yet effective) security element to your web
form in a very easy way.
Some External References
[advertisement] Try
Aggiorno for free, the assistant tool for web development you always wanted.