Click here to Skip to main content
13,736,547 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

94.5K views
3.8K downloads
14 bookmarked
Posted 8 Dec 2014
Licenced CPOL

How to Validate Recaptcha V2 Server side

, 8 Dec 2014
Rate this:
Please Sign up or sign in to vote.
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.

<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:

  <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:Button ID="btnLogin" runat="server" Text="Check Recaptcha" OnClick="btnLogin_Click"  TabIndex ="4"/>

On button Click, validate recaptcha:

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:

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

Get the response:

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:

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

MyObject is a class that has property Success:

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

After Deserialize JSON, you will get Response.

Now full validation function is like that:

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)

Share

About the Author

Prakash Bhatt (PB)
Web Developer Net creative mind
India India
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
QuestionVB version? Pin
19-Mar-18 5:30
member19-Mar-18 5:30 
QuestionPLease shed some light Pin
remandlo@gmail.com27-Sep-17 2:51
memberremandlo@gmail.com27-Sep-17 2:51 
PraiseWorked perfectly Pin
6-Sep-17 12:46
member6-Sep-17 12:46 
QuestionStill works on WebForms 25-05-2017 Pin
DarkSpy225-May-17 5:54
memberDarkSpy225-May-17 5:54 
Questionworked Pin
Member 131741054-May-17 19:35
memberMember 131741054-May-17 19:35 
PraiseThanks. Very helpful Pin
MarkWhitelist29-Mar-17 6:17
memberMarkWhitelist29-Mar-17 6:17 
QuestionGreat code, but I have a POST back issue Pin
16-Nov-15 14:50
member16-Nov-15 14:50 
QuestionAmazing Pin
13-Nov-15 4:47
member13-Nov-15 4:47 
QuestionGet Versus Post Pin
2-Jul-15 11:54
member2-Jul-15 11:54 
Suggestiona very helpful article Pin
Member 1163446722-Apr-15 21:30
memberMember 1163446722-Apr-15 21:30 
GeneralRe: a very helpful article Pin
its_Deebs11-May-15 8:37
memberits_Deebs11-May-15 8:37 
QuestionExcellent job! Pin
jbhopper3-Apr-15 8:28
memberjbhopper3-Apr-15 8:28 
GeneralThanks man! Pin
smoore43-Mar-15 8:01
membersmoore43-Mar-15 8:01 
QuestionThanxs a Bunch Pin
12-Jan-15 13:29
member12-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
memberpara350518-Dec-14 6:52 
AnswerRe: recaptcha returned invalid-input-response Pin
Member 1163446722-Apr-15 21:52
memberMember 1163446722-Apr-15 21:52 
QuestionWell Done Pin
J. Harlan Horn16-Dec-14 6:18
memberJ. Harlan Horn16-Dec-14 6:18 
GeneralAppreciation Pin
N. Binapani Devi9-Dec-14 18:34
memberN. Binapani Devi9-Dec-14 18:34 
GeneralRe: Appreciation Pin
Prakash Bhatt (PB)9-Dec-14 23:10
memberPrakash Bhatt (PB)9-Dec-14 23:10 
GeneralWow its greate! Thanku sir for posting such a greateful and helpful article Pin
8-Dec-14 19:46
member8-Dec-14 19:46 
GeneralVery good artical Pin
8-Dec-14 18:06
member8-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180920.1 | Last Updated 8 Dec 2014
Article Copyright 2014 by Prakash Bhatt (PB)
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid