如何在ASP.NET中实现reCaptcha V3

时间:2018-12-03 08:32:16

标签: asp.net recaptcha recaptcha-v3

有人在ASP.NET中拥有reCaptcha V3的完整实现演示吗?

我找到了这篇文章:Google Recaptcha v3 example demo

目前,我正在使用带有以下代码的reCaptcha V2:

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

在view.ascx页面上,我有:

<%@ 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>

4 个答案:

答案 0 :(得分:6)

最简单的

a)在cshtml中(在顶部)

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

}

b)在表单内部的cshtml中(恰好在/ form>之前:

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

c)Pagemodel类中的一个函数:

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

最后,在OnPostAsync内部开始:

            if (!ModelState.IsValid) return Page();
            else
            {
                if (!ReCaptchaPassed(Request.Form["foo"]))
                {
                    ModelState.AddModelError(string.Empty, "You failed the CAPTCHA.");
                    return Page();
                }
            }

答案 1 :(得分:4)

从前端(.aspx页面),您需要发送ajax请求,以将令牌传递给后端服务器。使用“ recaptcha.execute”,U可以获取响应,并使用ajax请求传递令牌。请检查代码块。

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

参考链接:  https://developers.google.com/recaptcha/docs/verify  https://developers.google.com/recaptcha/docs/display#js_api

现在在aspx.cs中,您需要编写一个“ [WebMethod]”以从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);

    }

要从google recapcha api获取响应,您需要使用httpClient使用异步调用。您还需要创建一个类,该类将包含相同的属性,例如响应字符串。获取“ responseString”后,您需要使用Newtonsoft.Json将响应转换为ResponseToken对象。 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; }
        }

答案 2 :(得分:2)

此页面上接受的答案是完全错误的!!! Google 会返回 0 到 1 之间的分数,以表明提交的内容可能是机器人还是人类。

返回的 success 属性仅表示正确处理了重新验证令牌。

应该检查的是 score 属性,而不是 success 属性

这些行是问题

if (JSONdata.success != "true")
    return false;

return true;

要比较的实际分数可能会在一个可以根据需要进行调整的变量中。 Google 建议从 0.5 开始。

因此代码应该更改为:

var recaptchaScore = 0.5m; // this could be in appSettings or whereever/however you are storing your constants

if (JSONdata.success != "true" || JSONdata.score <= recaptchaScore)
    return false;

return true;

当然,您可能希望在此答案中添加日志记录等,但这是所需的基本逻辑。

答案 3 :(得分:1)

有几个可用于ASP.Net的Recaptcha库。我选择使用reCAPTCHA.AspNetCore,因为它提供了HtmlHelper