Google reCAPTCHA Using JavaScript Approach

Introduction

In this article, we will learn how to integrate Google reCHAPTCHA using JavaScript code in a web application, in my case I am implementing functionality in the .NET MVC application. In order to integrate Google reCAPTCHA we require SiteKey and SecretKey for a web application which we can get from Google's Developer account. Please refer to my earlier article to get Google reCAPTCHA's keys.

Why Google reCAPTCHA is required?
it's a free service provided by Google with just a few configurations and setup. It helps our website from spam and attacks. As humans can easily solve "CAPTCHA" test which bots and malicious software can not help us to prevent from those attacks.
 
Let's start the integration of Google reCAPTCHA step by step.

Step 1

Import system.net library or namespace from references,

using System.Net;

Step 2

In order to use Google reCAPTCHA, we require key, secret, and response fields as a Model class. Please create the below modal class with exactly the same properties.

public class reCaptcha
{
    public string Response { get; set; }
    public string Secret = "<reCAPTCHA Secret Key>";
    public string Key = "<reCAPTCHA Site Key>";   
}

Step 3

To handle actions of Google reCAPTCHA, we need to declare a two-action method. These action methods are used to initialize CAPTCHA to our page and handle captcha responses from Google.

From below AjaxMethod - this action method will help us to handle calls from JavaScript AJAX call. Basically, it will call the Google reCAPTCHA API and verify the user, in return the response will be saved into the response property of the model class as a JSON value.

public class LoginController : Controller
{
    public ActionResult Login()
    {
        return View(new reCaptcha());
    }

    [HttpPost]
    public JsonResult AjaxMethod(string response)
    {
        reCaptcha recaptcha = new reCaptcha();
        string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + recaptcha.Secret + "&response=" + response;
        recaptcha.Response = (new WebClient()).DownloadString(url);
        return Json(recaptcha);
    }
}

Step 4

Now we need to configure AJAX call for verification and handle captcha verification on our VIEW(.cshtml) page.

Here we have to declare a captcha section in HTML that displays the captcha verification section, one hidden input box in order to save response, and one error message control that automatically handles while we face any issue or error while verification is done from the server.

Then after that we need to add an AJAX call which allows us to handle captcha verification on a page. Please refer to the below code in order to make it work.

@model CaptchaApp.Models.reCaptcha
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        .error {
            color: red;
        }
    </style>
</head>
<body>
    @* CAPTCHA section *@
    <div id="dvCaptcha"></div>
    <input type="hidden" id="hdCaptcha" />
    <span id="captchaError" class="error" style="display:none">Captcha validation is required.</span>
    <br />
    <input type="button" onclick="doCaptchaVerification()" value="Submit" />

    @* JavaScript Secetion *@

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
            asyncdefer=asyncdefer></script>
    <script type="text/javascript">
        var onloadCallback = function () {
            grecaptcha.render('dvCaptcha', {
                'sitekey': '@Model.Key',
                'callback': function (response) {
                    $.ajax({
                        type: "POST",
                        url: "/Login/AjaxMethod",
                        data: "{response: '" + response + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (r) {
                            var captchaResponse = jQuery.parseJSON(r.Response);
                            if (captchaResponse.success) {
                                $("#hdCaptcha").val(captchaResponse.success);
                                $("#captchaError").hide();
                            } else {
                                $("#hdCaptcha").val("");
                                $("#captchaError").show();
                                var error = captchaResponse["error-codes"][0];
                                $("#captchaError").html("reCAPTCHA error. " + error);
                            }
                        }
                    });
                }
            });
        };

        function doCaptchaVerification(){
            $("#captchaError").hide();
            if ($("#hdCaptcha").val() == "") {
                  $("#captchaError").show();
            }
        }
    </script>
</body>
</html>

Summary

This article helps you to integrate Google reCAPTCHA into your web application. This helps you to prevent bot, malicious software, or crawl attacks on websites. This Google reCAPTCHA service is totally free, easy, and integrated with very minimal code.


Similar Articles