How to implement reCaptcha V3 in ASP.NET

后端 未结 3 780
面向向阳花
面向向阳花 2020-12-08 17:07

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 reCap

相关标签:
3条回答
  • 2020-12-08 17:41

    Edit : I have added a demo project . Check this github repository . https://github.com/NIHAR-SARKAR/GoogleRecaptchav3-example-In-asp.net

    From frontend (.aspx page) you need to send ajax request to pass the token to backend server . Using "recaptcha.execute" U can get the response , and pass the token using ajax request .Please check the code block .

     <script src="http://www.google.com/recaptcha/api.js?render=recaptchaSiteKey"></script>
    <script>
     grecaptcha.ready(function() {
     grecaptcha.execute('recaptchaSiteKey', {action: 'homepage'}).then(function(token) {
    
                $.ajax({
                    //pass the toket to Webmethod using Ajax
                });
              });
         });
    </script>
    

    Reference link: https://developers.google.com/recaptcha/docs/verify https://developers.google.com/recaptcha/docs/display#js_api

    Now in the aspx.cs you need to write a "[WebMethod]" to receive the token from Ajax request .

        [WebMethod]
        public static void CaptchaVerify(string token)
        {
                var responseString = RecaptchaVerify(token);
                ResponseToken response = new ResponseToken();
                response = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
    
        }
    

    To get the response from google recapcha api u need to use async call using httpClient . you also need to create a class which will contain same properties like the response string . After getting the "responseString" u need to convert the response to ResponseToken object by using Newtonsoft.Json. response = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);

    private string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
    
    private string recaptchaSecret = googleRecaptchaSecret;
    
            public async Task<string> RecaptchaVerify(string recaptchaToken)
            {
                string url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
                using (var httpClient = new HttpClient())
                {
                    try
                    {
    
                        string responseString=  httpClient.GetStringAsync(url).Result;
                        return responseString;
    
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
    
    
            public class ResponseToken
            {
    
                public DateTime challenge_ts { get; set; }
                public float score { get; set; }
                public List<string> ErrorCodes { get; set; }
                public bool Success { get; set; }
                public string hostname { get; set; }
            }
    
    0 讨论(0)
  • 2020-12-08 17:57

    There are several Recaptcha libraries available for ASP.Net. I chose to use reCAPTCHA.AspNetCore because it provides an HtmlHelper.

    Please note that this library only supports one ReCatpcha per page, and it doesn't support Recaptcha v3 passive monitoring on non-form pages.

    0 讨论(0)
  • 2020-12-08 18:04

    The simplest:

    a) in cshtml (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>
    }
    

    b) in cshtml inside the form (just before /form>:

    <input type="hidden" id="foo" name="foo" />
    

    c) a function inside Pagemodel class:

    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")
            return false;
    
        return true;
    }
    

    Finally, inside OnPostAsync at the beginning:

    if (!ModelState.IsValid) 
        return Page();
    else
    {
        if (!ReCaptchaPassed(Request.Form["foo"]))
        {
            ModelState.AddModelError(string.Empty, "You failed the CAPTCHA.");
            return Page();
        }
    }
    
    0 讨论(0)
提交回复
热议问题