Wednesday, August 7, 2019

How to Integrate Google reCaptcha with asp.net

Step 1. Include following js at top of the .aspx page.
src="https://www.google.com/recaptcha/api.js?onload=renderRecaptcha&render=explicit" async defer

Step 2. Put following code into .aspx page.
Kindly put starting tag(<>) and ending tag(</>)
div class="form-group"
                                    div id="ReCaptchContainer" /div
                                   label id="lblMessage" runat="server" clientidmode="static" label
/div

Step 3. Put following javascript at the bottom of the .aspx page.


         var your_site_key = 'SITE_KEY';
        var renderRecaptcha = function () {
            grecaptcha.render('ReCaptchContainer', {
                'sitekey': your_site_key,
                'callback': reCaptchaCallback,
                theme: 'light', //light or dark   
                type: 'image',// image or audio   
                size: 'normal'//normal or compact   
            });
        };

        var reCaptchaCallback = function (response) {
            if (response !== '') {
                jQuery('#lblMessage').css('color', 'green').html('Success');
            }
        };

        jQuery('button[type="button"]').click(function (e) {
            var message = 'Please check the checkbox';
            if (typeof (grecaptcha) != 'undefined') {
                var response = grecaptcha.getResponse();
                (response.length === 0) ? (message = 'Captcha verification failed') : (message = 'Success!');
            }
            jQuery('#lblMessage').html(message);
            jQuery('#lblMessage').css('color', (message.toLowerCase() == 'success!') ? "green" : "red");
        });
   

Step 4. Put following function into .aspx.cs file

public bool IsReCaptchValid()
    {
        var result = false;
        var captchaResponse = Request.Form["g-recaptcha-response"];
        var secretKey = "SECRET_KEY";
        var apiUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
        var requestUri = string.Format(apiUrl, secretKey, captchaResponse);
        var request = (HttpWebRequest)WebRequest.Create(requestUri);

        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                JObject jResponse = JObject.Parse(stream.ReadToEnd());
                var isSuccess = jResponse.Value("success");
                result = (isSuccess) ? true : false;
            }
        }
        return result;
    }

Step 5. Validate IsReCaptchValid() function on Submit button click event

if (IsReCaptchValid())
        {
//Code for insert and send email to user/client
}
else
        {
            lblMessage.InnerHtml = (IsReCaptchValid())
         ? "span style='color:green'>Captcha verification success /span>"
         : "span style='color:red'>Captcha verification failed /span>";
        }

No comments: