How to implement reCaptcha V3 in ASP.NET

后端 未结 3 786
面向向阳花
面向向阳花 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 .

     
    
    

    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(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(responseString.Result);

    private string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
    
    private string recaptchaSecret = googleRecaptchaSecret;
    
            public async Task 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 ErrorCodes { get; set; }
                public bool Success { get; set; }
                public string hostname { get; set; }
            }
    

提交回复
热议问题