How to implement reCaptcha V3 in ASP.NET
The simplest implementation:
In your
cshtml
file (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>}
In your
cshtml
, inside the form (just before</form>
):<input type="hidden" id="foo" name="foo" />
A function inside your
Pagemodel
class. See the documentation for the response object: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" || JSONdata.score <= 0.5m) { return false; } return true;}
Finally, inside your
OnPostAsync()
handler, at the top:if (!ModelState.IsValid) { return Page();}else{ if (!ReCaptchaPassed(Request.Form["foo"])) { ModelState.AddModelError(string.Empty, "You failed the CAPTCHA."); return Page(); }}
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/verifyhttps://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; } }
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.