Recaptcha
Google (re)captcha is a very powerful tool to protect websites and endpoints from bots and spam attacks. We use reCAPTCHA v3 enterprise.
Note: Recaptcha is free up to 1 million assessments per month. After, it's $1 per 1,000 calls.
Visual render on frontend side
Unlike v2, reCAPTCHA v3 is invisible for website visitors. There are no challenges to solve on frontend. Instead, reCAPTCHA v3 continuously monitors each visitor's behavior to determine whether it's a human or a bot.
How to setup Google reCaptcha Enterprise
- Go to https://cloud.google.com/recaptcha-enterprise
- In the reCAPTCHA Enterprise section, click on Create key.
- Give a display name and choose a platform type.
- Add your domains. You must add at least one domain, you can add localhost and 127.0.0.1 for development environment.
- Click on Create key
- You should see the details of your recaptcha key. The ID is used on frontend side and the legacy secret key is used on backend side.
RecaptchaUtil
public class RecaptchaUtil
{
private static readonly HttpClient Client = new();
public static async Task VerifyToken(string token)
{
string secretKey = AppSettingsHelper.GetSetting("Recaptcha:SecretKey");
string googleUrl = AppSettingsHelper.GetSetting("Recaptcha:GoogleUrl");
var values = new Dictionary<string, string>
{
{ "secret", secretKey },
{ "response", token }
};
var content = new FormUrlEncodedContent(values);
var response = await Client.PostAsync(googleUrl, content);
string contentTest = await response.Content.ReadAsStringAsync();
var testSerialized = JsonSerializer.Deserialize<Dictionary<string, object>>(contentTest);
bool isValidToken = bool.Parse(testSerialized["success"].ToString());
if (!isValidToken)
{
throw new GeneralException("Recaptcha verification failed.");
}
}
}