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(); } }
The accepted answer on this page is totally wrong!!! Google returns a score between 0 and 1 to indicate whether the submission is likely to be a bot or likely to be a human.
The success
property returned only means that the recaptcha token was processed correctly.
It is the score
property that should be checked, not the success
property
These lines are the probelem
if (JSONdata.success != "true")
return false;
return true;
The actual score to compare will probably be in a variable that can be adjusted if need be. Google recommends starting with 0.5.
So the code should change to something like:
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;
Of course you will likely want to add logging etc to this answer but this is the bare logic that is required.
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; }
}