How to implement reCaptcha V3 in ASP.NET

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();
        }
    }
    

Leave a Comment