Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Recaptcha Jquery Ajax issue

I am using ASP.Net MVC to and trying to implement a Google reCaptcha object into a page.

I am trying to avoid the use of models in my forms, and want to just directly call a method using jquery ajax.

I have got the captcha to appear, but whatever I enter appears as null when inspecting the RecaptchaVerificationHelper object in debugger.

Any suggestions to keep it lightweight like I have it, but keep it working.

Note: Most of the logic has been stripped out here, just trying to get the captcha logic working.

CSHTML Sample:

@using Recaptcha.Web.Mvc;

<script type="text/javascript">
function createUser() {

            $.ajax({
                type: "POST",
                url: 'CreateUser',
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response.Success == true) {
                        alert("success");
                        //redirectSuccess();
                    } else {
                        alert("failed");
                    }
                },
                error: function (err) {
                    commonError(err);
                }
            });

    }
</script>

@Html.Recaptcha(publicKey: "6LdxcPgSAA...", theme: Recaptcha.Web.RecaptchaTheme.Clean);
<br />
<input type="button" value="Submit" onclick="createUser();" style="margin-right:300px;" />

CS Server Code Sample:

public ActionResult User()
        {
            return View();
        }

public JsonResult CreateUser()
        {
            Wrapper.ValidationResponse response = new Wrapper.ValidationResponse();
            response.Success = true;

            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {

                response.Success = false;
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                response.Success = false;
            }

                try
                {
                    //removed logic
                    return Json(response);
                }
                catch (Exception ex)
                {
                    response.Success = false;
                    response.Message = "Failed to create new user. Please contact us if the issue persists.";
                    return Json(response);
                }
        }

Thanks in Advance,

like image 264
Cyassin Avatar asked Dec 27 '14 11:12

Cyassin


Video Answer


2 Answers

After going mad for over a week, I finally got a working solution directly using the developers API.

What I did was use the jsAPI and manually add the captcha control using the API to the page. On submit, I captured the recaptcha response and sent it server side.

From server side I then validated the request following the API Instructions and using this tutorial found here: http://www.codeproject.com/Tips/851004/How-to-Validate-Recaptcha-V-Server-side I then sent the request and handled the response accordingly.

HTML:

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

<script type="text/javascript">
    var captcharesponse = grecaptcha.getResponse();


            $.ajax({
                type: "POST",
                url: 'CreateUser',

                data: "{captcharesponse:" + JSON.stringify(captcharesponse) + "}",
                contentType: "application/json; charset=utf-8",
                success: function (response) {

                    if (response.Success == true) {
                        alert("success");

                    } else {
                        alert("failed");

                    }

                },
                error: function (err) {
                    commonError(err);
                }
            });
        }
</script>

<div class="g-recaptcha"
                 data-sitekey="[public key here]"></div>
            <br />
<input type="button" value="Submit" onclick="createUser();" style="margin-right:300px;" />

CS:

[HttpPost]
        public JsonResult CreateUser(string captcharesponse)
        {
            Wrapper.ValidationResponse response = new Wrapper.ValidationResponse();
            response.Success = true;

            if (Recaptcha.Validate.Check(captcharesponse) == false)
            {
                response.Success = false;
            }

                try
                {
                    //removed logic
                    return Json(response);
                }
                catch (Exception ex)
                {
                    response.Success = false;
                    response.Message = "Failed to create new user. Please contact us if the issue persists.";
                    return Json(response);
                }
        }



public class Validate
    {
        public static bool Check(string response)
        {
            //string Response = HttpContext.Current.Request.QueryString["g-recaptcha-response"];//Getting Response String Append to Post Method
            bool Valid = false;
            //Request to Google Server
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create
            (" https://www.google.com/recaptcha/api/siteverify?secret=" + WebConfigurationManager.AppSettings["recaptchaPrivateKey"] + "&response=" + response);
            try
            {
                //Google recaptcha Response
                using (WebResponse wResponse = req.GetResponse())
                {

                    using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
                    {
                        string jsonResponse = readStream.ReadToEnd();

                        JavaScriptSerializer js = new JavaScriptSerializer();
                        MyObject data = js.Deserialize<MyObject>(jsonResponse);// Deserialize Json

                        Valid = Convert.ToBoolean(data.success);
                    }
                }

                return Valid;
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }
    }

    public class MyObject
    {
        public string success { get; set; }
    }
like image 53
Cyassin Avatar answered Sep 17 '22 03:09

Cyassin


Your controller Method

public JsonResult CreateUser() //<-- CamelCase

does not match with ajax call

url: 'createUser', //<-- small case
like image 34
agentpx Avatar answered Sep 19 '22 03:09

agentpx