Integration Of Google reCAPTCHA V2 In Websites

Overview
 
In this article, I am going to explore the integration of Google reCAPTCHA V2 with ASP.NET applications as well as how to customize the   reCAPTCHA widget.
 
What is reCAPTCHA
 
Google reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
 
reCAPTCHA offers more than just spam protection. Every time our CAPTCHAs are solved, that human effort helps digitize text, annotate images, and build machine learning datasets. This, in turn, helps preserve books, improve maps, and solve hard AI problems.

Tough on boats, Easy on humans 
Google reCAPTCHA 
 
Prerequisites 
 
Here, I will create a sample ASP.NET website to integrate Google reCAPTCHA. So, the following are the prerequisites for this article. 
  • We should have a Google account where we can register our sites for reCAPTCHA
  • Visual Studio [ optional ]
Here, I am using Visual Studio 2015 for creating an ASP.NET application but it's not mandatory. We may use either the latest version or any older if we want to validate reCAPTCHA at the server-side as well.
 
Site Registration for reCAPTCHA
 
reCAPTCHA API's sitekey and secretkey are required. 
 
So, first, we need to register our site/domain with Google reCAPTHCA v2 API to get the site key and secret key. So now, I am going to register our domains (localhost, programcafe.in) where I will use these keys for reCAPTCHA integration. Click here for domain registration. 
 
register-domain-for-recaptcha
 
In the above image, we can see, there are three types of reCAPTCHA, i.e.,
  • reCAPTCHA v2
  • Invisible reCAPTCHA
  • reCAPTCHA Android
But I have checked first one that is reCAPTCHA v2 and typed two domains localhost and programcafe.in . Now, click on the "Register" button after accepting its terms and conditions.
 
Note

We can mention multiple domains along with localhost. After clicking on Register button, the following screen will appear which contains reCAPTCHA Site key and Secret key.
 
secret-keys 
 
On this screen, we have an option for Advanced Settings for security preference. We can customize it according to our requirement.
 
Security Preference 
 
Now, we have all the things ready to integrate the reCAPTCHA on websites.
 
For this article, I am going to create an empty website with name reCAPTCHA and after that, I will add a new page named Default.aspx.
 
About reCAPTCHA Auto Rendering
 
Automatic Rendering Widget 
  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <div class="g-recaptcha" data-sitekey="6Lfn8DoUAAAAAEuzI65jbXXNaewCS9BwO_XXXXXXXX"></div>          
  4.     </form>  
  5.     <script src='https://www.google.com/recaptcha/api.js'></script>  
  6. </body>  
This is the easiest way to rendering a reCaptcha on a web page. In the above code snippet, we can see that there is a div element having two attributes class and data-sitekey and both these attributes are mandatory.
  • g-recaptcha is mandatory to make render recaptcha widget, we can not use own class name. 

  • data-sitekey is the key which is provided by Google reCAPTCHA for the domains which are mentioned at the time of reCAPTCHA v2 registration.
Let's execute this page to see how reCAPTCHA is showing.
 
auto-render-recaptcha-widget 
 
Apart from these two mandatory attributes, Google provides some additionals attributes to customize the reCAPTCHA widget according to our choice/requirement. 
 
Following are the list of some optional attributes which can be used to customize the reCAPTCHA widget.
  • data-theme
    we can use either light or dark theme. The default theme is light.

    eg.
    1. <div data-theme="light"  ></div>  
    2. <div data-theme="dark"  ></div>  
     dark-theme

  • data-type
    data type for recaptcha challenges edither may be image or audio but the default data-type is image.
    1. <div class="g-recaptcha" data-type="image" data-sitekey="site_key_value" />  
    data-type-image
    1. <div class="g-recaptcha" data-type="audio" data-sitekey="site_key_value" />    
    data-type-audio

  • data-size
    it can be compact or normal but the default size is normal.
    1. <div class="g-recaptcha" data-size="normal" data-sitekey="site_key_value" />    
    2.   
    3. <div class="g-recaptcha" data-size="compact" data-sitekey="site_key_value" />    
    data-size-view

  • data-tabindex
    We can set the tabindex to make access easier
Google reCAPTCHA API Parameters
 
Following are the reCAPTCHA API Parameters and all these parameters are optional.
  • calback - The name of your callback function to be executed once all the dependencies have loaded.
  • render - Whether to render the widget explicitly. Defaults to onload, which will render the widget in the first g-recaptcha tag it finds.
  • hl - Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. 
reCAPTCHA Integration With Website

Rendering reCAPTCHA Explicitly
 
Step 1
 
Create an empty ASP.NET website and a new page Default.aspx and put the following code snippet inside the body tag.
 
Default.aspx 
  1. <div id="ReCaptchContainer"></div>  
  2. <label id="lblMessage" runat="server" clientidmode="static"></label>  
  3. <br />  
  4. <button type="button" >Submit</button>  
In the above HTML code snippet, I have taken a div tag where recaptha widget will be rendered and there is a label to display validation message for recaptcha on button click.
 
Step 2
 
Refer the reCaptcha API script on the page. For this article, I am putting this script at the bottom of the body.
  1. <!--Refere reCaptcha API-->    
  2.     <script src="https://www.google.com/recaptcha/api.js" async defer></script>   
In this article, we are going to render the widget explicitly so we need to add onload and render parameters with reCaptcha API script.
 
Here, the onload parameter's value is renderRecaptcha which is a JavaScript function that renders the reCaptcha widget and the render value is explicit which show that render the widget explicitly by calling the function renderRecaptcha. 
  1. <!--Refere reCaptcha API-->    
  2.     <script src="https://www.google.com/recaptcha/api.js?onload=renderRecaptcha&render=explicit" async defer></script>  
Step 3
 
Now, add the follwing script for reCAPTCHA render and it's callback functions.
  1. <script  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>  
  2.  
  3. <script type="text/javascript">  
  4.     var your_site_key = '<%= ConfigurationManager.AppSettings["SiteKey"]%>';  
  5.     var renderRecaptcha = function () {  
  6.         grecaptcha.render('ReCaptchContainer', {  
  7.             'sitekey': your_site_key,  
  8.             'callback': reCaptchaCallback,  
  9.             theme: 'light'//light or dark    
  10.             type: 'image',// image or audio    
  11.             size: 'normal'//normal or compact    
  12.         });  
  13.     };  
  14.   
  15.     var reCaptchaCallback = function (response) {  
  16.         if (response !== '') {  
  17.             jQuery('#lblMessage').css('color''green').html('Success');  
  18.         }  
  19.     };  
  20.   
  21.     jQuery('button[type="button"]').click(function(e) {  
  22.         var message = 'Please checck the checkbox';  
  23.         if (typeof (grecaptcha) != 'undefined') {  
  24.             var response = grecaptcha.getResponse();  
  25.             (response.length === 0) ? (message = 'Captcha verification failed') : (message = 'Success!');  
  26.         }  
  27.         jQuery('#lblMessage').html(message);  
  28.         jQuery('#lblMessage').css('color', (message.toLowerCase() == 'success!') ? "green" : "red");  
  29.     });  
  30.   
  31. </script>  
Step 4
 
Let us run the page to test the reCAPTCHA functionality.
 
 
 
Step 4 Server Side Validation
 
For server-side validation, we need to call reCaptcha siteverify API along with parameters secretkey and response (recaptcha response after form submit).
 
Folliwing are the API URL.
 
https://www.google.com/recaptcha/api/siteverify?secret=<secret-key>&response=<captcha-response>  
  1. public bool IsReCaptchValid()  
  2. {  
  3.     var result = false;  
  4.     var captchaResponse = Request.Form["g-recaptcha-response"];  
  5.     var secretKey = ConfigurationManager.AppSettings["SecretKey"];  
  6.     var apiUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";  
  7.     var requestUri = string.Format(apiUrl, secretKey, captchaResponse);  
  8.     var request = (HttpWebRequest)WebRequest.Create(requestUri);  
  9.   
  10.     using(WebResponse response = request.GetResponse())  
  11.     {  
  12.         using (StreamReader stream = new StreamReader(response.GetResponseStream()))  
  13.         {  
  14.             JObject jResponse = JObject.Parse(stream.ReadToEnd());  
  15.             var isSuccess = jResponse.Value<bool>("success");  
  16.             result = (isSuccess) ? true : false;  
  17.         }  
  18.     }  
  19.     return result;  
  20. }  
Now, call this method on button click to validate the reCaptcha input.
  1. protected void btnTry_Click(object sender, EventArgs e)  
  2. {  
  3.     lblMessage.InnerHtml = (IsReCaptchValid())   
  4.         ? "<span style='color:green'>Captcha verification success</span>"  
  5.         : "<span style='color:red'>Captcha verification failed</span>";  
  6. }  
Step 4
 
Now, execute the program to test the server-side validation.

 
In the above JSON result object, "success: True" indicates that reCAPTCHA challenges validation success.
 
If anyone wants to see some sites where google reCAPTHCA is used
Summary

In this article, we learned what Google reCAPTCHA is, how to register our site for reCAPTHCA, how to integrate reCAPTCHA widget with the web page, how to validate reCAPTCHA challenges on the client side as well as server side in an ASP.NET application.
 
In an upcoming article, I will share about Invisible reCAPTCHA.

Up Next
    Ebook Download
    View all
    Learn
    View all