Click here to Skip to main content
15,881,719 members
Articles / Web Development / ASP.NET
Tip/Trick

How to Validate Recaptcha V2 Server side

Rate me:
Please Sign up or sign in to vote.
4.97/5 (20 votes)
8 Dec 2014CPOL2 min read 155.5K   4.6K   18   25
Recaptcha V2 easy to use and easy to implement

Introduction

Recaptcha is mainly used to stop spam on website and verify the user is human or not.

Here is a sample.

Advantages of recaptcha V2 are:

  • Smooth experience with captcha
  • Many options for captcha, i.e., Image, audio

Background

While implementing new google recaptcha V2, I had some problems because there is no documentation provided on recaptcha website.

Using the Code

To use the recaptcha, first you need to register at https://www.google.com/recaptcha login or create a new account. Than go to “Register a new site” and insert your domain name and title. You will get two Keys Site key and Secret key. Site key is used in HTML which server to user means front end & Secret key for communication between Google server and website it should be secret.

After getting Keys, you need to Integrate the site key in HTML. So first of all, paste the JavaScript snippet code in head section of your front end HTML.

HTML
<head id="Head1" runat="server">
    <title>Admin Login:WPC</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
 
    <script type="text/javascript" 
    src='https://www.google.com/recaptcha/api.js'></script>
</head>

After adding that, you need to add a div in your web page where you want recaptcha with your site key:

HTML
  <div class="g-recaptcha" 
data-sitekey="YOUR SITE KEY"></div>

Now frontend implementation of recaptcha is over, you can run HTML and see recaptcha, so go to code section.

When user submits the recaptcha form, the user gets a response POST parameter. To verify the User:

[g-recaptcha-response]

You should send a GET request to Google along with the response and Secret key.

Now, I am attaching a button on web page to submit form:

ASP.NET
<asp:Button ID="btnLogin" runat="server" Text="Check Recaptcha" OnClick="btnLogin_Click"  TabIndex ="4"/>

On button Click, validate recaptcha:

C#
if(   Validate())
        {    lblmsg.Text = "Valid Recaptcha";
            lblmsg.ForeColor = System.Drawing.Color.Green;
        }

     else
     {  lblmsg.Text = "Not Valid Recaptcha";
         lblmsg.ForeColor = System.Drawing.Color.Red;
     }

Send Get request to server along with secret key and response and get response:

C#
 HttpWebRequest req = (HttpWebRequest)WebRequest.Create
(" https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRATE KEY &response=" + Response);

Get the response:

C#
using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))

You will get response in JSON Format. Like:

{
  "success": true|false,
  "error-codes": [...]   // optional
}

So you need to Deserialize the JSON:

C#
JavaScriptSerializer js = new JavaScriptSerializer();
                    MyObject data = js.Deserialize<MyObject>(jsonResponse);// Deserialize Json

MyObject is a class that has property Success:

C#
public class MyObject {
        public string success { get; set; }
}

After Deserialize JSON, you will get Response.

Now full validation function is like that:

C#
public bool Validate()
 {
     string Response = Request["g-recaptcha-response"];//Getting Response String Append to Post Method
     bool Valid = false;
     //Request to Google Server
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create
     (" https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRATE KEY &response=" + Response);
     try
     {
         //Google recaptcha Response
         using (WebResponse wResponse = req.GetResponse())
         {

             using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
             {
                 string jsonResponse = readStream.ReadToEnd();

                 JavaScriptSerializer js = new JavaScriptSerializer();
                 MyObject data = js.Deserialize<MyObject>(jsonResponse);// Deserialize Json

                 Valid = Convert.ToBoolean(data.success);
             }
         }

         return Valid;
     }
     catch (WebException ex)
     {
         throw ex;
     }
 }

Points of Interest

This is my first article on CodeProject and I quite enjoyed writing this tip. You can refer to the attached code file along with this. Please point out mistakes and suggestions are most welcome.

History

  • v/1.0 08 Dec 2014

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Net creative mind
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAwesome Pin
snashter23-Feb-21 1:04
snashter23-Feb-21 1:04 
QuestionValidate multiple recaptcha (V2) on the same page Pin
Alpesh viradiya2-May-20 17:07
Alpesh viradiya2-May-20 17:07 
QuestionVB version? Pin
Member 1373472719-Mar-18 5:30
Member 1373472719-Mar-18 5:30 
AnswerRe: VB version? Pin
fastarasta6-Nov-19 16:39
fastarasta6-Nov-19 16:39 
QuestionPLease shed some light Pin
remandlo@gmail.com27-Sep-17 2:51
remandlo@gmail.com27-Sep-17 2:51 
PraiseWorked perfectly Pin
Member 87466096-Sep-17 12:46
Member 87466096-Sep-17 12:46 
QuestionStill works on WebForms 25-05-2017 Pin
DarkSpy225-May-17 5:54
DarkSpy225-May-17 5:54 
Questionworked Pin
Member 131741054-May-17 19:35
Member 131741054-May-17 19:35 
PraiseThanks. Very helpful Pin
MarkWhitelist29-Mar-17 6:17
MarkWhitelist29-Mar-17 6:17 
QuestionGreat code, but I have a POST back issue Pin
Member 1134971816-Nov-15 14:50
Member 1134971816-Nov-15 14:50 
QuestionAmazing Pin
Member 1211441113-Nov-15 4:47
Member 1211441113-Nov-15 4:47 
QuestionGet Versus Post Pin
Member 118097552-Jul-15 11:54
Member 118097552-Jul-15 11:54 
Suggestiona very helpful article Pin
Member 1163446722-Apr-15 21:30
Member 1163446722-Apr-15 21:30 
GeneralRe: a very helpful article Pin
its_Deebs11-May-15 8:37
its_Deebs11-May-15 8:37 
QuestionExcellent job! Pin
jbhopper3-Apr-15 8:28
jbhopper3-Apr-15 8:28 
GeneralThanks man! Pin
smoore43-Mar-15 8:01
smoore43-Mar-15 8:01 
QuestionThanxs a Bunch Pin
Member 867524712-Jan-15 13:29
Member 867524712-Jan-15 13:29 
QuestionIs it really Recaptcha version 2 ?? Pin
Tarun Jaiswal6-Jan-15 18:14
professionalTarun Jaiswal6-Jan-15 18:14 
Questionrecaptcha returned invalid-input-response Pin
para350518-Dec-14 6:52
para350518-Dec-14 6:52 
AnswerRe: recaptcha returned invalid-input-response Pin
Member 1163446722-Apr-15 21:52
Member 1163446722-Apr-15 21:52 
QuestionWell Done Pin
J. Harlan Horn16-Dec-14 6:18
J. Harlan Horn16-Dec-14 6:18 
GeneralAppreciation Pin
N. Binapani Devi9-Dec-14 18:34
N. Binapani Devi9-Dec-14 18:34 
GeneralRe: Appreciation Pin
Prakash Bhatt (PB)9-Dec-14 23:10
Prakash Bhatt (PB)9-Dec-14 23:10 
GeneralWow its greate! Thanku sir for posting such a greateful and helpful article Pin
Member 112965358-Dec-14 19:46
Member 112965358-Dec-14 19:46 
GeneralVery good artical Pin
Member 112963148-Dec-14 18:06
Member 112963148-Dec-14 18:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.