How to implement reCaptcha V3 in ASP.NET

巧了我就是萌 提交于 2019-11-27 16:43:54

问题


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>

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/53590011/how-to-implement-recaptcha-v3-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!