Implement Google reCAPTCHA In ASP.NET MVC

Introduction

reCAPTCHA is a CAPTCHA-like system designed to establish that a computer user is human (normally in order to protect websites from bots) and, at the same time, ReCAPTCHA lets you embed a CAPTCHA in your web pages in order to protect them against spam and other types of automated abuse. Recaptcha is owned by Google.

This article shows how to integrate reCaptcha version 2.0 into an ASP.Net MVC website.


Prerequisites

Visual Studio, a web browser and a valid Google account. (The example uses Visual Studio 2015 Update 3, .Net Framework 4.5 and Firefox web browser 50.1.0 ).

Prior knowledge of HTML, .Net and ASP.Net MVC is required.

Step 1 Get API Key And Secret

Login to your Google account. Then go  here.

If it shows “Invisible? Incredible. Coming soon. The Invisible reCAPTCHA. “

Click continue and do not sign up.

You will be redirected to here then click on Get reCAPTCHA.


Now the Admin page loads. It shows a list of sites you’ve registered for reCaptcha.


Enter your details in the register a new site section. Add a label to identify the site and add a list of domains. Also remember to add localhost if you intend to test it on your local machine ( PC ).

Click register and you will be provided with your site key and secret key.


Step 2 Add Recaptcha To Your View

  • Automatically render the reCAPTCHA widget

Open the view page on which you intend to show the recaptcha. In the head section of the page add the script.

  1. <script src='https://www.google.com/recaptcha/api.js'></script>   

Then add,

  1. <div class="g-recaptcha" data-sitekey="xxxxxxxxx"></div>   

to where to want it to display on the page.

  • If you wish to show recaptcha widget on javascript event:

Specify your onload callback function. This function will get called when all the dependencies have loaded. 

  1. <script type="text/javascript">  
  2.     var onloadCallback = function() {  
  3.         alert("reCaptcha is ready !!!");  
  4.     };  
  5. </script>   

Insert the Javascript resource, setting the onload parameter to the name of your onload callback function and the render parameter to explicit. 

  1. <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>  
  2. </script>  

When your callback is executed, you can call the grecaptcha.render method from the Javascript API.

Note

Your onload callback function must be defined before the reCAPTCHA API loads. To ensure there are no race conditions,

  • order your scripts with the callback first, and then reCAPTCHA
  • use the async and defer parameters in the script tags.

Note

Ensure you add the reCaptcha widget inside the form tag.

Step 3 Verify Recatcha Response

Now go to the controller and the action that will handle the submit event of the view.

In the action we will need to add FormCollection in the parameter as g-recaptcha-response cannot be made into a parameter as .Net doesn’t allow – (hyphen/dash) in the variable name.

We then verify the response by post it to this URL.

Google returns JSON in the below format, 

  1. {  
  2. "success"true|false,  
  3. "challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)  
  4. "hostname": string, // the hostname of the site where the reCAPTCHA was solved  
  5. "error-codes": [...] // optional  
  6. }   

When success is true, it means the Captcha is verified, if it's false then user has not passed reCaptcha test, you can check error-codes for additional errors.

I’ve provided a sample implementation. Please check code below,

  1. [HttpPost]  
  2. public ActionResult ABCD(FormCollection form) {  
  3.     if (string.IsNullOrWhiteSpace(form["g-recaptcha-response"])) {  
  4.         //Throw error as required  
  5.     }  
  6.     ReCaptchaResponse reCaptchaResponse = VerifyCaptcha("xxxxSecret Keyxxxx", form["g-recaptcha-response"]);  
  7.     if (!reCaptchaResponse.success) {  
  8.         //Throw error as required  
  9.         //You can also log errors returned from google in reCaptchaResponse.error_codes  
  10.     }..........  
  11. }  
  12. //Function ... you can create it in a different class  
  13. public static ReCaptchaResponse VerifyCaptcha(string secret, string response) {  
  14.         if (request != null) {  
  15.             using(System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient()) {  
  16.                 var values = new Dictionary < string,  
  17.                     string > {  
  18.                         {  
  19.                             "secret",  
  20.                             secret  
  21.                         },  
  22.                         {  
  23.                             "response",  
  24.                             response  
  25.                         }  
  26.                     };  
  27.                 var content = new System.Net.Http.FormUrlEncodedContent(values);  
  28.                 var Response = hc.PostAsync(“https: //www.google.com/recaptcha/api/siteverify”, content).Result;  
  29.                     var responseString = Response.Content.ReadAsStringAsync().Result;  
  30.                     if (!string.IsNullOrWhiteSpace(responseString)) {  
  31.                         ReCaptchaResponse response = JsonConvert.DeserializeObject < ReCaptchaResponse > (responseString);  
  32.                         return response;  
  33.                     } else  
  34.                     //Throw error as required  
  35.                 }  
  36.             }  
  37.             else  
  38.             //Throw error as required  
  39.         }  
  40.         //You can use http://json2csharp.com/ to create C# classes from JSON  
  41.         //Note error-codes is an invalid name for a variable in C# so we use _ and then add JsonProperty to it  
  42.         public class ReCaptchaResponse {  
  43.             public bool success {  
  44.                 get;  
  45.                 set;  
  46.             }  
  47.             public string challenge_ts {  
  48.                 get;  
  49.                 set;  
  50.             }  
  51.             public string hostname {  
  52.                 get;  
  53.                 set;  
  54.             }  
  55.             [JsonProperty(PropertyName = "error-codes")]  
  56.             public List < string > error_codes {  
  57.                 get;  
  58.                 set;  
  59.             }  
  60.         }   
Error codeDescription
missing-input-secretThe secret parameter is missing.
invalid-input-secretThe secret parameter is invalid or malformed.
missing-input-responseThe response parameter is missing.
invalid-input-responseThe response parameter is invalid or malformed.

Future

Google soon plans on releasing Invisible reCAPTCHA. It’s now available as Beta.

References

https://developers.google.com/recaptcha/intro
https://www.google.com/recaptcha
https://en.wikipedia.org/wiki/ReCAPTCHA

Up Next
    Ebook Download
    View all
    Learn
    View all