How to implement reCaptcha V3 in ASP.NET

后端 未结 3 787
面向向阳花
面向向阳花 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 18:04

    The simplest:

    a) in cshtml (at the top)

    @section Scripts
    {
        
        
    }
    

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

    
    

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

提交回复
热议问题