JavaScript | Validate Google reCAPTCHA

watch_later Saturday, September 4, 2021

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 that we can get from Google's Developer account. Please refer to my earlier article to get Google reCAPTCHA's keys.

JavaScript | Validate Google reCAPTCHA

Why Google reCAPTCHA is required?

it's a free service provided by Google with just a few configurations and setups. It helps our website from spam and attacks. As humans can easily solve the "CAPTCHA" test which bots and malicious software can not help us to prevent 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 { getset; }
    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-familyArial;
            font-size10pt;
        }
 
        .error {
            colorred;
        }
    </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.


Author Credit

Article Type :Guest Article
Author :Ankit Kanojia
Tags :Google, reCAPTCHA
Article Date :02-07-2021
Article Publish Date :04-09-2021
Note : All content of this article are copyright of their author.

Codingzee provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

If you have any questions regarding this article/blog you can contact us on codingzee@gmail.com

sentiment_satisfied Emoticon