Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement reCaptcha V3 in ASP.NET

Does anyone have a full implementation demo of reCaptcha V3 in ASP.NET?

I found this article: Google Recaptcha v3 example demo

At the moment I am using reCaptcha V2 with the following code:

public bool RecaptchaValidate()
    {
        string Response = Request.Form["g-recaptcha-response"];//Getting Response String Append to Post Method
        bool Valid = false;
        //Request to Google Server
        var CaptchaSiteKey = Settings["NewUserRegCaptchaSecretSiteKey"].ToString();
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create
        (" https://www.google.com/recaptcha/api/siteverify?secret=" + CaptchaSiteKey + "&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();
                    ReCaptchaObject data = js.Deserialize<ReCaptchaObject>(jsonResponse);// Deserialize Json

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

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

On the view.ascx page I have:

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

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

<scrip>
var recap = grecaptcha.getResponse();
if (recap.length == 0) {
                $("#verifyhuman").css("display", "block");
            }
</script>

 <div class="g-recaptcha" data-sitekey="<%=ReCaptchaPublicKey%>" id="recaptcha" data-callback="recaptchaCallback"></div>
like image 256
Tig7r Avatar asked Dec 03 '18 08:12

Tig7r


People also ask

Which is better reCAPTCHA v2 or v3?

What is the difference between reCAPTCHA v2 and v3? ReCAPTCHA v2 requires the user to click the “I'm not a robot” checkbox and can serve the user an image recognition challenge. ReCAPTCHA v3 runs in the background and generates a score based on a user's behavior. The higher the score, the more likely the user is human.


Video Answer


1 Answers

The simplest implementation:

  1. In your cshtml file (at the top)

    @section Scripts
    {
        <script src="https://www.google.com/recaptcha/api.js?render=your site key"></script>
        <script>
            grecaptcha.ready(function () {
                grecaptcha.execute('your site key', { action: 'homepage' }).then(function (token) {
                    document.getElementById("foo").value = token;
                });
            });
        </script>
    }
    
  2. In your cshtml, inside the form (just before </form>):

    <input type="hidden" id="foo" name="foo" />
    
  3. A function inside your Pagemodel class. See the documentation for the response object:

    public static bool ReCaptchaPassed(string gRecaptchaResponse)
    {
        HttpClient httpClient = new HttpClient();
    
        var res = httpClient.GetAsync($"https://www.google.com/recaptcha/api/siteverify?secret=your secret key no quotes&response={gRecaptchaResponse}").Result;
    
        if (res.StatusCode != HttpStatusCode.OK) 
        {
            return false;
        }
        string JSONres = res.Content.ReadAsStringAsync().Result;
        dynamic JSONdata = JObject.Parse(JSONres);
    
        if (JSONdata.success != "true" || JSONdata.score <= 0.5m)
        {
            return false;
        }
    
        return true;
    }
    
  1. Finally, inside your OnPostAsync() handler, at the top:

    if (!ModelState.IsValid) 
    {
        return Page();
    }
    else
    {
        if (!ReCaptchaPassed(Request.Form["foo"]))
        {
            ModelState.AddModelError(string.Empty, "You failed the CAPTCHA.");
            return Page();
        }
    }
    
like image 103
nefen Avatar answered Sep 28 '22 13:09

nefen