Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Validate Recaptcha V2 Server side

0.00/5 (No votes)
8 Dec 2014 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here