How to integrate Google’s "I’m not a robot" reCAPTCHA in ASP.NET

In this article you will learn how to use Google’s new reCAPTCHA “I’m not a robot” in ASP.NET applications. Google’s reCAPTCHA is a free service which protects your website from spam, abuse and bots. Google has updated their CAPTCHA API version to reCAPTCHA API 2.0

I am not a Robot

The new version of reCAPTCHA is very secure with attractive layout. With the help of new version users can attest as they are human without inputting blurry numbers or solving problems. With just a single click Google’s reCPATCH will confirm you are not a robot. This new version also called as No CAPTCHA reCPATCHA.

No CAPTCHA reCAPTCHA

Integration

The first step to integrate the Google’s reCAPTCHA is to register your website domain. Go to the below website link and click on Get reCAPTCHA button.


Google reCAPTCHA Register a new site

Input your application name in label field, your website domain name under Domains field and click on ‘Register’ button.

Note: If you want to test reCAPTCHA in your local machine, just add localhost in Domains field.
Upon successful registration you will get Site Key and Secret Key as shown below.

reCAPTCHA Site Key and Secret Key

Site Key: It is used to display reCAPTCHA widget in your site.
Secret Key: It is used to verify whether the user response to reCAPTCHA is valid or not.

Display reCAPTCHA

The next is display the reCAPTCHA widget on your site. We will see this step practically by having a login screen and verify reCAPTCHA before user login.

Copy and paste the below script reference before closing </head> tag.

[pre class="brush:html; toolbar: false;" title=""]
<script src='https://www.google.com/recaptcha/api.js'></script>
[/pre]
Copy and paste the below snippet before closing the </form> tag where you want to appear the reCAPTCHA widget.

[pre class="brush:html; toolbar: false;" title=""]
<div class="g-recaptcha" data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP">
</div>
[/pre]
Here is the sample login from with reCAPTCHA widget in my .aspx page

[pre class="brush:html; toolbar: false;" title="simple login form with reCAPTCHA"]
    <form id="form1" runat="server">
        <div>
            <h2><u>Dotnet 4 Techies</u></h2>
            <h3>Login Now</h3>
        </div>
        <div>
            <table>
                <tr>
                    <td>Username:</td>
                    <td>
                        <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td>
                        <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </div>
        <div class="g-recaptcha" data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP"></div>
        <br />
        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
    </form>
[/pre]
Verify reCAPTCHA

When you submit a form which includes the reCAPTCHA, you will get a response in a variable called g-recaptcha-response.

To confirm whether user has been verified with reCAPTCHA, you need to send a GET call to below URL by including your secret key, response from g-recaptcha-response variable and user IP address.


Here is the code on how to verify the user response to reCAPTCHA upon clicking login button.

[pre class="brush:c-sharp; toolbar: false;" title="code to verify reCAPTCHA upon login"]
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;

            bool isValidCaptcha = ValidateReCaptcha(ref errorMessage);

            if (isValidCaptcha)
            {
                //connect to your db and verfiy login details
            }
            else
            {
                //show an errorMessage and YOU ARE A ROBOT
            }
        }

        public bool ValidateReCaptcha(ref string errorMessage)
        {
            var gresponse = Request["g-recaptcha-response"];
            string secret = "6LcqFg8UAAAAAO_FQuzRejzk9fa004PO86sy8d0";
            string ipAddress = GetIpAddress();

            var client = new WebClient();

            string url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}
                                         &response={1}&remoteip={2}", secret, gresponse, ipAddress);

            var response = client.DownloadString(url);

            var captchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(response);

            if (captchaResponse.Success)
            {
                return true;
            }
            else
            {
                var error = captchaResponse.ErrorCodes[0].ToLower();
                switch (error)
                {
                    case ("missing-input-secret"):
                        errorMessage = "The secret key parameter is missing.";
                        break;
                    case ("invalid-input-secret"):
                        errorMessage = "The given secret key parameter is invalid.";
                        break;
                    case ("missing-input-response"):
                        errorMessage = "The g-recaptcha-response parameter is missing.";
                        break;
                    case ("invalid-input-response"):
                        errorMessage = "The given g-recaptcha-response parameter is invalid.";
                        break;
                    default:
                        errorMessage = "reCAPTCHA Error. Please try again!";
                        break;
                }

                return false;
            }
        }

        string GetIpAddress()
        {
            var ipAddress = string.Empty;

            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
            else if (!string.IsNullOrEmpty(Request.UserHostAddress))
            {
                ipAddress = Request.UserHostAddress;
            }

            return ipAddress;
        }

        public class ReCaptchaResponse
        {
            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("error-codes")]
            public List<string> ErrorCodes { get; set; }
        }
[/pre]

reCAPTCHA widget and verify reCAPTCHA

That’s it. Hope you understand the Google’s reCAPTCHA integration process. The given implementation is not only specific to ASP.NET, the same you can convert into any other language app as per your need. 

If you have any questions please discuss then using comments section below. Thanks…

11 comments:

  1. Hi.

    I have used this code but it keeps crashing on the when getting the URL ValidateReCaptcha(ref string errorMessage) method with "Input string was not in a correct format" error message. Is there something i am missing?

    ReplyDelete
  2. {"The operation has timed out"} in this line var response = client.DownloadString(url);

    ReplyDelete
  3. string url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}
    &response={1}&remoteip={2}", secret, gresponse, ipAddress);

    cannot use local variabel 'respose', pleasee help me.. how to handle it ...

    ReplyDelete
  4. What is the: JsonConvert. I got error on this line

    ReplyDelete
  5. You have to download Newtonsoft.Json.dll from https://www.newtonsoft.com/json and add an using in the login page (or you can use a nuget package)

    ReplyDelete
  6. Share your google page on additional social media channels: If you are not already, you should take full advantage of as many of the popular (and appropriate) social media channels as you possibly can.reviews on google

    ReplyDelete
  7. I have got the timeout issue, when deploy in the live server,
    working fine in the local domain.

    please suggest solution.

    ReplyDelete
    Replies
    1. Your firewall is probably blocking out going request to google.com, can you visit the url in a browser on the production machine?

      Delete
  8. Can I get the Asp.net core code for this implementation?? Thanks

    ReplyDelete
  9. This website and I conceive this internet site is really informative ! Keep on putting up! anti captcha

    ReplyDelete

Powered by Blogger.