The captcha control is a self contained Web control. It is easy to use and secure. It prevents automated registration.
I was given a task to add a captcha validation on a registration page. I found an article in CodeProject that is right on the target. The article solved that task, but I wasn't very happy about having to have an ASPX page reference, a need for a session variable, not easily customizable, distorting the whole image instead of letter. I'm in my vacation and spending a night creating a control to share and for future references.
Using the Code
Add an assembly reference to the control on a page:
<%@ Register Namespace="CaptchaControl" Assembly="CaptchaControl" TagPrefix="cc" />
CaptchaControl tag to the page:
<cc:CaptchaControl ID="captcha" runat="server"
CharCount="5" Width="200" CharSet="AllLowerCaseLetters"/>
On postback, call
captcha.Validate(userinput) -- where
userinput is what user typed.
The default values for the control are:
IgnoreCase = true;
CharCount = 3;
this.Width = new Unit(120);
this.Height = new Unit(50);
Password = this.GetType().AssemblyQualifiedName;
CharSet = CharSets.NumberAndLetters;
When two users or browser windows of the page are open, after a user (
user1) input passes the validation and the other user refreshes the page, if
user1 hits the submit button again with the input from the new image, the user will get "validation failed".
This is because the code in the
viewstate does not match the code in the new image any more. This problem shouldn't be a problem in the real application because mostly we would want a page redirect to a different page on successful validation. This problem can be resolved if we append the image file name with a guid id, but this approach introduces a new problem that is having a lot of images being created.
Each character needs about 40px of space, if you increase the
1, you should increase
40 to prevent character image cutoffs.
Points of Interest
It was fun to add noise and distort the character bitmap image. This is one of the major advantage features over the article I read. Any cool way of distorting the image, please post it here, I'll add it to the project.
This control stores the encrypted code in the
viewstate, the password can be set in the HTML markup or programmatically.
My next step on this subject is trying to create an HTML helper function for ASP.NET MVC.
- 9th December, 2009: Initial post