Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

CAPTCHA - prevent bots and automatic submissions in ASP.NET

What is CAPTCHA

In this article I will explain the use of CAPTCHA and provide a sample class that you can use in your projects. So, what is CAPTCHA?

 

Standing for "Completely Automated Public Turing test to tell Computers and Humans Apart", A CAPTCHA is a program that can generate and grade tests that most humans can pass, but current computer programs can't pass. For example, humans can read distorted text as the one shown below, but current computer programs can't:

 

CAPTCHAs are used to prevent bots from performing actions which might be used to make a profit on the part of the person running a bot. Most often, this relates to spam. For example, free email accounts (such as those provided by Google or Yahoo) can be used to send spam, so these sites use CAPTCHAs to prohibit bots from registering.

Likewise, many sites which display email addresses could be used by spammers, so CAPTCHAs protect the addresses. Other spam related applications include CAPTCHAs to prevent blog comments, or accounts on other systems that might allow link spam.

So, do you see why CAPTCHAs are important today?

Working the Code: CAPTCHA ASP.NET application example

The first thing is to create the CAPTCHA functionality. With the sample project that you'll find with this article, you'll find a sample Visual Studio .NET project CaptchaImage zipped and ready to be used in your applications. Compile it to produce and use an assembly with your Web applications. The major method in the project is GenerateImage.cs that does all the creation of our CAPTCHA image.

Coming back to point, let us now create a web application that will utilize this CAPTCHA assembly. There is Upload & Compression sample from a File Upload & Compression in ASP.Net tutorial, and will use CAPTCHA sample application to make it more secure. Using CAPTCHA will let me make sure that bots won't get to submit the form.

The rest of the screen is the same, except the new Image Component as well as the TextBox. The Image is a System.Web.UI.WebControls.Image control that will display our Captcha Image, generating it on load. The textbox is for the user to enter the text as he sees it in the image.

First of all add a new web-page to the project. Name it GetImage.aspx and put the following in Code-Behind.

Partial Class GetImage
    Inherits System.Web.UI.Page
 
    Private Sub Page_Load(..., ...) Handles MyBase.Load
        'Create a CAPTCHA image using the text stored in the Session object.
        Dim ci As New CaptchaImage.CaptchaImage(
Me.Session("CaptchaImageText"),
200, 50, "Century Schoolbook")
 
        Me.Response.Clear()
        Me.Response.ContentType = "image/jpeg"
 
        ci.Image.Save(Me.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg)
 
        ci.Dispose()
    End Sub

End Class

What happens here is that I am passing in text read from a session to a new CaptchaImage object. I am making use of the CaptchaImage Assembly, whose code is included in the sample. The page loads, creates a captcha image, and writes it back.

Now, switch back to Default.aspx, and open the Properties of our Image control. There will be a property named "ImageUrl". Set that to GetImage.aspx and save. What happens here is that when the page loads, i.e. when Default.aspx loads, the Image control sends to GetImage.aspx to retrieve the image, which will be our CaptchaImage.

Don't get confused, for you will begin to understand this much better when you'll play around with the code. Now, switch to Default.aspx.vb, and create an object of System.Random type.

Private rand As New System.Random

This will be used to generate a random number, that'll then be used to generate the CaptchaImage.

Protected Sub Page_Load(..., ... ) Handles Me.Load
If Not Page.IsPostBack Then
Me.Session("CaptchaImageText") = GenerateRandomCode()
End If
End Sub
 
Private Function GenerateRandomCode() As String
Dim s As String = ""
For i As Integer = 0 To 5
s = s + Me.rand.Next(10).ToString()
Next
Return s End Function

The GenerateRandomCode method returns a 6 digit number and returns it as a string. Look at the Page_Load event, when the page is loaded, I set a Session Object "CaptchaImageText" to the value returned by the GeneratedRandomCode method. The Page_Load method will create the image each time the page loads.

Now... when you are executing the Upload code, or whatever functionality it is that you have on your page, all you need to do is:

Dim tempString As String = Me.Session("CaptchaImageText") If String.Compare(tempString, Me.txtCaptcha.Text.Trim()) = 0 Then
    
'Code Functionality Here.
Else
    Me.lblResult.Text = "Validation Text was not correct."
    Me.Session("CaptchaImageText") = GenerateRandomCode()
End If

The code above gets the current RandomString, that our Captcha is based upon, and checks whether it is equal to what the user entered. If, not then we show an error and reset the image for post-back, otherwise, we continue with execution of code.

Running the application, these are two of the few Captcha Images that I get:


Used the right way, and on the right form, this security feature can save you from a lot of trouble. If you need support for sounds, different types of images or you simply have no time to reinvent the wheel, you can get BotDetect, the best software in this category. I hope you found this article enlightening and enjoyable.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |