Apply Latest Google reCAPTCHA Using ASP.NET MVC 4.0 In Your Real Time Project

INTRODUCTION

Google introduced a new tool for online users to keep their online properties safe and fine - reCAPTCHA -  that you can easily add to your forum, registration form , blog, Online Payment Transaction, Internet Banking etc. Also, reCAPTCHA protects your site from spam.

How it works

Before information or Data posts back to the Server , GOOGLE reCAPTCHA asks online users some questions to avoid spam and abuse, and keeps your online sites safe.

GOOGLE reCAPTCHA Image Ref


Steps To complete this requirement

Step 1

First, create a basic type of MVC application named “SatyaLatestGoogleRecaptcha”.


Step 2

Check reference of Newtonsoft.Json in your "References" folder. Otherwise, you can install from NuGet Packages. This is nothing but a dll file “Newtonsoft.Json.dll”.


How to open NuGet to install

Right click on "References" folder and select "Manage NuGet Packages" and search for this Newtonsoft.Json.dll file and install.




Step 3

Add a Controller class file named “HomeController.cs”.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using Newtonsoft.Json; //These two namespaces are required For Below mentioned class file WebClient and JObject.  
  8. using Newtonsoft.Json.Linq;  
  9. namespace SatyaLatestGoogleRecaptcha.Controllers {  
  10.     public class HomeController: Controller {  
  11.         //  
  12.         // GET: /Home/  
  13.         public ActionResult Index() {  
  14.                 return View();  
  15.             }  
  16.             [HttpPost]  
  17.         public ActionResult Post() {  
  18.             var Yourresponse = Request["g-recaptcha-response"]; //Validate Google recaptcha here.  
  19.             string YoursecretKey = "Put Your Own Secret Key Here"//Put Your Secret Key .  
  20.             var client = new WebClient();  
  21.             var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", YoursecretKey, Yourresponse)); //Pass your Response and Secret Key here.  
  22.             var obj = JObject.Parse(result); //Result In True or False.  
  23.             var humanstatus = (bool) obj.SelectToken("success");  
  24.             //check the status is true or not to identify you are a robot or not.  
  25.             if (humanstatus == true//Condition put for message show based on True or false.  
  26.             {  
  27.                 ViewBag.Notify = "SatyaPrakash's Google reCaptcha validated Successfully";  
  28.             } else {  
  29.                 ViewBag.Notify = "SatyaPrakash's Google reCaptcha not validated Successfully";  
  30.             }  
  31.             //When you post form for save data , check both the model validation and google recaptcha validation.  
  32.             return View("Index"); // Here I used Index View.  
  33.         }  
  34.     }  
  35. }   

The above mentioned code is described with red highlighted Comment Line.


Step 4

Add a View cshtml file named “Index.cshtml” in "Views/Home" folder.

Code Ref 

  1. @ {  
  2.     ViewBag.Title = "Satyaprakash Latest Google Recaptcha";  
  3. } < h2 style = "color:red" > Satyaprakash Samantaray 's New Way For Robot Identification</h2> < fieldset > < legend style = "font-family:Arial Black;color:blue" > Test For Robot Identification < /legend> < div > @using(Html.BeginForm("Post""Home", FormMethod.Post)) { < div class = "g-recaptcha"  
  4.     data - sitekey = "Put Your Own Site Key Here" > < /div>  
  5.         //As you created your own site key here.  
  6.         < input type = "submit"  
  7.     value = "Post"  
  8.     style = "color:Navy;font-family:Arial; font-size:large" / >  
  9. } < /div>  
  10. @if(ViewBag.Notify != null//Put Some Javascript alert will show before show your status of Your reCAPTCHA is executed successfully or not.  
  11. { < script type = "text/javascript" > alert("Click Ok To See Your Status !"); < /script>  
  12. } < span style = "display:block; font-size:20px;color:green" >  
  13.     //Viewbag message comes from HomeController.cs file  
  14.     if (humanstatus == true) {  
  15.         ViewBag.Notify = "SatyaPrakash's Google reCaptcha validated Successfully";  
  16.     }  
  17. else {  
  18.     ViewBag.Notify = "SatyaPrakash's Google reCaptcha not validated Successfully";  
  19. //  
  20. @ViewBag.Notify < /span> < /fieldset> < script src = 'https://www.google.com/recaptcha/api.js'  
  21. type = "text/javascript" > < /script>  
  22. //This javascript file should be added for to access this reCAPTCHA api.  

The Above Mentioned code is described with red highlighted Comment Line.


Step 5

This step will show you how to create your Own Site Key and Secret Key .

Site Key Should be mentioned in Index.cshtml .

Secret key Should be mentioned in HomeController.cs .

Pic 1

Go to this link https://www.google.com/recaptcha/intro/index.html


Pic 2

Then click on the top right corner Get reCaptcha button.


Pic 3

Then Login yto our Gmail Account and sign in.


Pic 4

After signing in Click Continue.


Pic 5

Click continue and open in new tab


Pic 6

Click On Again Get reCAPTCHA


Pic 7

You will get a Key Setting Box .

Here You should put your own Label Name .

Domains Should be localhost because if anyone wants to get Google reCaptcha API for localhost then you must enter “localhost” in the Domains text area otherwise your personal domain name or address .

Your Owners name is Your recent sign in mail id address .


Pic 8

You will get Adding reCAPTCHA to your site.

  1. Keys Where you will get your own site key and own secret key.
  2. Client side integration Tips for how to add client side in these two keys.
  3. Server Side Integration Tips to how to add server side in  these two keys .

Pic 9

Get Your Site Key and Secret Key From Key Option

When You Expand your Key Option you already have created your own site key and secret key.

  • Site Key Use this the Html code when your site serves the users.
  • Secret Key use this for communication between your site and Google .

Always Keep It Secret .


Pic 10

Now after expanding all options this view will come like this

i.e. Key , Client side integration , Server Side Integration.


Pic 11

The OutPut Actual Google reCAPTCHA will look this


OutPut

At page load time the below link will come

How to set start page -- you can check my previous blogs.

http://localhost:60516/Home/Index

Home : Controller name .

Index : Controller action method name .


Then Click On Google reCAPTCHA Check box , See what will happen.


Then Google reCAPTCHA asks you some Questions to identify if you are a robot or not.


After selecting the correct images Google reCAPTCHA asked for,  then the checkbox will show a green check.


If you don't select any proper image then it will give you another chance to  answer with the message -> “Please try again”.


After selecting the proper images then click Post Button.

See what will happen

The link is changed to http://localhost:60516/Home/Post

Post is another controller action method in HomeController.cs file

As well as in Index.Cshtml file.

I.e.

  1. @using(Html.BeginForm("Post""Home", FormMethod.Post))  
  2. {   
  3.   < div class = "g-recaptcha"  
  4.     data - sitekey = "6Lez8RMUAAAAADj4bd_DhySD2FI4pPydWHllVIga" > < /div> < input type = "submit"  
  5.     value = "Post"  
  6.     style = "color:Navy;font-family:Arial; font-size:large" / >  
  7. }  

You will get a Alert Message after clicking Post Button

i.e.

  1. @if(ViewBag.Notify != null)   
  2. {   
  3.   < script type = "text/javascript" > alert("Click Ok To See Your Status !"); < /script>  
  4. }  

Then you will see a Successful Message with green mark after selecting all images properly in Google reCAPTCHA.


If you don't select Google reCAPTCHA checkbox and select only the post button, then you will get a Failure message with green mark.




We can ADD the latest google reCAPTCHA in our real time project.

The output will look like as mentioned above.

If there is no SiteKey And Secret Key then the out put Will look like this.

The message will say “Invalid Site Key” because there is no site key In Index.Cshtml.


After Clicking Post Button Button , if there are no site keys or secret keys then the output will look like this.

The message will say  “Invalid Site Key” because there is no site key in Index.Cshtml.


I checked for both link Urls before button click and after button click

http://localhost:60516/Home/index
http://localhost:60516/Home/Post

ATTACHED FILE TIPS

  1. For Solution File and Code Related .
    Refer Solution File : SatyaLatestGoogleRecaptcha.zip

  2. Steps for creating your own Site Key and Secret Key as I mentioned above.
    Refer Image Files : SatyaLatestGoogleRecaptcha Pics.zip


Similar Articles