Saturday 15 August 2020

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.

<script src='https://www.google.com/recaptcha/api.js'></script>


Copy and paste the below snippet before closing the </form> tag where you want to appear the reCAPTCHA widget.

<div class="g-recaptcha" 
data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP">
</div>


Here is the sample login from with reCAPTCHA widget in my .aspx page

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


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.

        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; }
        }


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. 

No comments:

Post a Comment