Integration of Google ReCaptcha With MVC4 Application

It is in trend these days to verify that a user is a human or not and the easiest and most used option to do this is to have Google ReCaptcha in your application. This article elaborates how to integrate Google reCaptcha in a MVC4 application. After going through with this article you may get the benefit of this rich feature.

ReCaptcha

To understand what reCaptcha is we first need to define the term “Captcha“.

Captcha is a test made of an image and distorted text that must be solved by human users when they want to subscribe to websites that want to ensure the user is a human being and not a bot or a computer (= preventing spam). Excerpt taken from link.

The initial step to integrate Google reCaptcha is to register your site/domain to receive public/private keys. To reach that level merely paste this URL in a browser.

As soon as you hit the preceding given URL it gives you given the following screen.

site

I have registered mine as shown in the following screen shot:

screen shot

This is how it looks after registering this feature and provides public/private keys along with a reference file and API to use further.

reference file and API

You have registered and now ready to use this excellent feature.

Step 1

Kindly put you public key and private key in the web.config file as shown in the following image:

shown below in image

Step 2

Kindly ensure a few points in order to integrate Google reCaptcha on the .cshtml page as shown in the following image:

image
Source Code Create.cshtml page is given below:

  1. @model MVCSample.Models.EmpRegistration  
  2. @{  
  3.     ViewBag.Title = "Create";  
  4. }  
  5. <h2>  
  6.     Create</h2>  
  7. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>  
  8. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>  
  9.   
  10. <script type="text/javascript" src='https://www.google.com/recaptcha/api.js'></script>  
  11.   
  12. @using (Html.BeginForm())  
  13. {  
  14.     @Html.ValidationSummary(true)  
  15.     <fieldset>  
  16.         <legend>EmpRegistration</legend>  
  17.         <div class="editor-label">  
  18.             @Html.LabelFor(model => model.Id)  
  19.         </div>  
  20.         <div class="editor-field">  
  21.           @*  @Html.EditorFor(model => model.Id)  
  22.             @Htm*@l.ValidationMessageFor(model => model.Id)  
  23.         </div>  
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.Name)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.Name)  
  29.             @Html.ValidationMessageFor(model => model.Name)  
  30.         </div>  
  31.         <div class="editor-label">  
  32.             @Html.LabelFor(model => model.Address)  
  33.         </div>  
  34.         <div class="editor-field">  
  35.             @Html.EditorFor(model => model.Address)  
  36.             @Html.ValidationMessageFor(model => model.Address)  
  37.         </div>  
  38.         <div class="editor-label">  
  39.             @Html.LabelFor(model => model.City)  
  40.         </div>  
  41.         <div class="editor-field">  
  42.             @Html.EditorFor(model => model.City)  
  43.             @Html.ValidationMessageFor(model => model.City)  
  44.         </div>  
  45.         <div class="g-recaptcha"  data-sitekey=@System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>  
  46.           
  47.         <p>  
  48.             <input type="submit" value="Create" />  
  49.         </p>  
  50.     </fieldset>  
  51. }  
  52. <div>  
  53.     @Html.ActionLink("Back to List""Index")  
  54. </div>  

Step 3

Verify that the user response as reCAPTCHA is generated and resolved by a user. The following API URL is used to verify the user response.

In the preceding API URL the secret and response parameters are required and whereas the remoteip is optional. We have a response class to verify the user response.

response parameters

I have created a POST method in the Index action in the RegisterController to verify the user response.

Here the code segment is shown below:

  1. [HttpPost]  
  2. public ActionResult Create(EmpRegistration modelEmpRegistration)  
  3. {  
  4.     bool isCapthcaValid = ValidateCaptcha(Request["g-recaptcha-response"]);  
  5.       
  6.     try  
  7.     {  
  8.         if (isCapthcaValid)  
  9.         {  
  10.             if (ModelState.IsValid)  
  11.             {  
  12.                 //dbContext.AddToEmpRegistrations(modelEmpRegistration);  
  13.                 //dbContext.SaveChanges();  
  14.   
  15.             }  
  16.             return RedirectToAction("Create");  
  17.         }  
  18.         else  
  19.         {  
  20.             return Content("You have put wrong Captcha,Please ensure the authenticity !!!");  
  21.         }  
  22.         //return RedirectToAction("Index");  
  23.     }  
  24.     catch  
  25.     {  
  26.         return View();  
  27.     }  
  28. }  
  29.   
  30. public static bool ValidateCaptcha(string response)  
  31. {  
  32.     //secret that was generated in key value pair  
  33.     string secret = WebConfigurationManager.AppSettings["recaptchaPrivateKey"];  
  34.   
  35.     var client = new WebClient();  
  36.     var reply =  client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));  
  37.   
  38.     var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);  
  39.   
  40.     return Convert.ToBoolean(captchaResponse.Success);  
  41.   
  42. }  

Step 4

Run the application and press F5. It'll open a page as shown in the image below:

Run the application

Click on “Create New” => It will open a page as depicted below:

Create New

Case 1

Fill in the desired details and check the checkbox. Just prefix the I'm not a robot. It will open the popup to select the choice.

select food

If you have provide the correct details it will consider you to be a human and shows the following screen as confirmation.

Create

Click on the Create button and it reaches the code segment and executes the code.

Create button

As you can see from the image above it has returned “success” from the server meaning it worked perfectly.

Note: After executing successfully it returns to the create page again. I've used this page for demonstration purposes only.

Case 2

If you don't check the checkbox prefix to the message “I'm not a robot” and press Enter. It goes to the code and verifies the authenticity and it returns false. It means you are not a valid user.

authenticity

valid user

Please find the source code as an attachment.

Integration of Google ReCaptcha with MVC4 Application - Running Application.

I hope it will help to resolve your issue.

Thanks.

Up Next
    Ebook Download
    View all
    Learn
    View all