shami sheikh
shami sheikh

Reputation: 562

Increase reCaptcha Security

I am using google recaptcha v2 in my application I'd integrate it in client side. Here is my code

<script>
    var onloadCallback = function () {
        grecaptcha.render('recaptcha', {
            'sitekey': '6Lc_qmcUAAAAAJW_kALWjxcxcvxcxcvxcvxc',
            'callback': reCaptchaCallback,
        });
    };

    var reCaptchaCallback = function (response) {
        if (response !== '') {
            console.log(response);
        }
    };

    function getReCaptchaRes() {
        var message = 'Please check the checkbox';
        if (typeof (grecaptcha) != 'undefined') {
            var response = grecaptcha.getResponse();
            (response.length === 0) ? (message = 'Captcha verification failed') : (message = '');
        }
        $('#reCaptchaLblMsg').html(message).css('color', "red");
        return !(response.length === 0)
    }
    
    
    
     submitHandler: function (form) {

                            // call the google recaptcha validation
                            if (getReCaptchaRes()) {

                                $('.spinner-holder').css('display', 'block');
                                $("#myAjaxRegisterModal2 input[type='submit']").val("Saving ...").attr('disabled', 'disabled');

                                var __RequestVerificationToken = $('[name="__RequestVerificationToken"]').val();

                                var RegisterData = {
                                    __RequestVerificationToken: __RequestVerificationToken,
                                    ProfileCreatedFor: $('#ddlProfileCreatedFor').val(),
                                    GroomBrideName: $('#txtName').val(),
                                    Mobile: $('#txtMobile').val(),
                                    EmailID: $('#txtEmail').val(),
                                    Height: $('#ddlHeight').val(),
                                    Gender: $("input[name='Gender']:checked").val(),
                                    MaritalStatus: $('#ddlMaritalStatus').val(),
                                    DOBMonth: $('#ddlMonth').val(),
                                    DOBDate: $('#ddlDate').val(),
                                    DOBYear: $('#ddlYear').val(),
                                    State: $('#ddlUserState').val(),
                                    City: $('#ddlCity').val(),
                                    Section: $('#ddlUserSection').val(),
                                    DivisonText: $('#DivisonText').val(),
                                    Password: $('#ConfirmPassword').val()
                                }

                                //form.submit();
                                $.ajax({
                                    url: "/Home/RegisterNewMemberByJson",
                                    type: "POST",
                                    data: RegisterData,
                                    dataType: 'json',
                                    success: function (data) {
                                        if (data == "Error") {
                                            window.location.href = "/Home/Index";
                                        }
                                        else if (data == true) {
                                            $('#myAjaxRegisterModal2').modal('hide');
                                            RegisterPopUp();
                                        }
                                        else {
                                            $('.spinner-holder').hide();
                                            $("#myAjaxRegisterModal2 input[type='submit']").val("Save").removeAttr("disabled");
                                            $('#ageErrorMsg').text(data);
                                        }
                                    }
                                });

                            }
                        }
<div class="clearfix"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>

But my concern is if I will change response from browser console then I can hit the ajax method multiple times using a loop. So how can I prevent it to hit my ajax method into loop Or there is something wrong with my captcha integration.

My another concern is is it possible to check the captcha response on the client side as well as on the server side. if possible then how. Please help me any kind of help will be appreciated.

Upvotes: 1

Views: 742

Answers (1)

shami sheikh
shami sheikh

Reputation: 562

Now I can answer my own question. I was making a stupid mistake I was not sending the response through ajax and was trying to get the response into my method on controller through [g-recaptcha-response].

Here is the updated code.

 public JsonResult RegisterNewMemberByJson(ReligionAndEthinicityModel RegisterData)
    {
        if (ModelState.IsValid)
        {
            try
            {
                bool captchaIsvalid = IsReCaptchValid(RegisterData.cResponse);
                if (captchaIsvalid)
                {


public bool IsReCaptchValid(string cResponse)
    {
        var result = false;
        var captchaResponse = cResponse;
        var secretKey = Convert.ToString(ConfigurationManager.AppSettings["RecaptchaKey"]);
        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<bool>("success");
                result = (isSuccess) ? true : false;
            }
        }
        return result;
    }

Upvotes: 1

Related Questions