Optional sidebar menu
Social media
Contact information
Address

September 2017: Change of address in progress.

Email

[email protected]

Phone

+353 87 2446653

Sulware Blog


Using Googles new reCAPTHCA api with ASP.NET

07/12/2014 Posted by Brendan O'Sullivan | Comments(9)

Key Areas:

ASP.NET, C#, Software Development, Tutorials, Web Development
Using Googles new reCAPTHCA api with ASP.NET

Google's new reCAPTCHA api is a nice little nugget for your websites.

Basically it removes the need to have those Captcha based security questions on your input forms. You know the ones I'm talking about here. Where you have to enter the text you see on an image to prove you're not an internet auto bot trying to bombard sites with junk input.

These Captchas are pretty good at keeping bots away but over time the bots they're trying to block have become more and more sophisticated and are starting to break through the Captcha wall.

We're a massive fan of Google here at Sulware, and always love to play with their new api's. The Google reCAPTCHA api increases your input forms chances of blocking the bots yet at the same time makes the process much much easier for your users by replacing the annoying image check based Captcha with a simple checkbox stating, "I'm not a robot".

We've already implemented this on our Sulware site, (See the comment form below this article for example). Pretty simple eh? So far so good and we're seeing a marked decrease in bot break throughs.

Hurray for google.

Implementation is pretty straight forward. The rest of this article discusses how to implement the code in a typical ASP.NET site. For our own Sulware clients, if all continues to go fine with the api, (which it should), we'll be looking at rolling this out as part of our next CMS update and will visit each clients input form as required.

ASP.NET Implementation of the Google API reCAPTCHA

  1. Go to the Google reCATCHA page here. You'll be able to read up more on the reCAPTCHA process there, but for now click on the "Get reCAPTCHA" link at the top of the page. You'll need to be logged on with your Google account to complete this so go ahead and logon (or register with Google if you have to !)
  2. Each site you use the api on will need to be setup here and each site gets a Site Key and Secret Key which you'll need to provide to the code later.
  3. The next screen will give you step by step instructions as to what needs to go into your HTML front end. Basically the script import line for the javascript file and a <div> component for the form where you want the actual user input checkbox and question to appear. Note, the <Div> component references the Secret Key, so just make sure you copy it correctly. Go ahead and open up your aspx file where you form resides and paste the lines into the relevant sections.

At this point your form is ready. The user can click the checkbox and submit the form. However we have to tell the back end that receives the data that the reCAPTCHA has worked (or not!). To do that the code added above adds in another variable in the forms postback called "g-recaptcha-response"
You'll next need to go to the backend code for the form submit event handler, check the above variable, and then pass the contents of that variable over to a google web api address. This will in turn return back a result which you can then check and take action against. Here's some sample code which does all that.

if (Request["g-recaptcha-response"] != null && Request["g-recaptcha-response"] !="") 
{
// the google web api call takes three parameters:
// 1) Your websites secret which you got when setting up the domain name to use the service
// 2) The value of the g-recaptcha-response that's coming back in the subbmitted form
// 3) The requesting users IP address
//

string sCatchaResponse = Request["g-recaptcha-response"];
string sSecret = <set to the secret you got when registering the site>
string sIPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();

// Next create a WebClient instance to call the web api and get the result...
//
System.Net.WebClient wc = new System.Net.WebClient();
string sRequest = String.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}", sSecret, sCatchaResponse, sIPAddress);
string sResponse = wc.DownloadString(sRequest);

// The result comes back as a JSON object. I've created a simple GoogleResponse object to hold this information
// and am using the JavaScriptSerializer to deserialize the response accordingly...
//
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
GoogleResponse response = serializer.Deserialize<GoogleResponse>(sResponse);

// Now we can just check if the call succeeded or failed and take the necessary action
//
if (!response.success)
{
// just output an error on the front end here...
//
return;
}
}
else
{
// ok if you're here, you basically didn't check that bot question on the form.
// Tell the user to do so and resubmit the form...
//
return;
}

// from here you've gotten past the reCaptcha so do your normal form handling here...

 

The above code references a simple GoogleResponse object class which I've defined as: 

private class GoogleResponse 
{
public bool success;
public string errorcodes;
}

 That's about all there is to it. Have a play and let us know what you think.

About the Author

Brendan O'Sullivan

Brendan O'Sullivan is a computer science graduate of DIT and has been working professionally as a software/web developer, Systems Architect and IT consultant since 1993. After spending 3 years with IBM, he went on to found Sulware in 1996. He has worked with a vast array of companies from large multi nationals to small family run businesses. Brendan also holds technical directorships with a number of other Irish based companies.

Comments(9)
wasim
16/02/2015 13:26:47
Nice work it really help me alot.
Ashish Narnoli
03/02/2015 10:03:54
Really great article! Thank you so much..
Tom Henrich
20/01/2015 12:50:33
Tsai no space should be there. Thats what ended up being my issue. good luck -Tom
Brendan O'Sullivan
20/01/2015 09:21:45
Thanks for the comments folks. Bishy, you're right that link shouldn't have a space, and I removed accordingly. Tom and Jak, apologies I'll take a look at that issue with reading the return codes. In our implementations we just have a black and white approach to calling the code, either it works or it doesn't, but I'll take a look at the return code issue and come back to you.
bishy tsai
20/01/2015 04:02:57
Hi, thank you your share. But there is a issue in "https://www.google.com/recaptcha/api/siteverify? secret={0}&response={1}&remoteip={2}". I think there is no blank between ? and secret, right?
Tom Henrich
07/01/2015 04:12:26
Good article. Got me going in the right direction. Ran into the same issue as Jak though. Any idea would be great.
Brendan
28/12/2014 01:54:47
Thanks for the comments guys. Jak, that is odd. I'll take a look and come back to you.
Alin Oancea
27/12/2014 12:54:54
Good job! This work for me. :)
Jak Hammond
18/12/2014 10:25:14
Great article! Really helped me understand how to get all this ticking along nicely server-side. One question I do have, when the response is mapped to your GoogleResponse class, from what I've seen at least, the error-codes from the JSON object aren't being mapped to the respective ErrorCodes field in your class. I can only imagine this is because the names differ between the JSON and the field? I have tried to work round this using DataContract, but an exception is being thrown when it attempts to map the JSON to the class still. Have you got any advice on this one?

Add a Comment


Name:
Email:
Website:
Notify of New Replies:
Add a new comment:

Latest Posts

Chapters

Topics

Latest Comments

Archives