reCAPTCHA

29.06.2018 von robert@riwa4.de
/blog/artikel/recaptcha

reCAPTCHA Dokumentation

In order to prevent trolling robots from making entries on a web page, the so-called captchas have been around for a long time to distinguish robots from humans. To do this, it is usually necessary to recognize letters or numbers in a text field - for the user this is more than annoying. 

reCAPTCHAs The idea was to use the time and energy that users spend on this for meaningful things. In the meantime, the company has been taken over by Google and the focus has been changed somewhat: It is largely automatically recognized whether a person is really clicking on the web page or not, and only in exceptional cases do tasks have to be solved when typing, such as recognizing traffic signs. I have now tried the installation of the service once.

Deutsch Français Espagnol Portuguese

The documentary is a bit sparse, but basically it's simple. I initially built this into an internal test page and as soon as I need it, I can easily enable that. To help, there is also a ready-made NuGET package for ASP.NET Core that you can use. Actually trivial, but still helpful to see how it's done:

The configuration is done in a separate section, so that you don't have to insert the sitekey manually everywhere. In order for the options to be available in a Razor page, you can call the configuration in Startup:

services.Configure<RecaptchaSettings>(Configuration.GetSection("RecaptchaSettings"));
services.AddTransient<IRecaptchaService, RecaptchaService>();

And in the page:

@inject IOptions<RecaptchaSettings> RecaptchaSettings

Then you can insert the captcha like this:

<div class="g-recaptcha" data-sitekey="@RecaptchaSettings.Value.SiteKey"></div>

You can then simply use @RecaptchaSettings.Value.SiteKey to reference the sitekey. And in the Razor page, you can use dependency injection to get the IRecaptchaService interface, which provides the Validate function. These are called to validate the call.

It will look like this:

        public async Task<IActionResult> OnPostAsync()
{
bool captchaValid = await _recaptcha.Validate(Request);
if (!captchaValid)
{
ModelState.AddModelError("reCaptcha", "Bitte das reCaptcha bestätigen.");
}
if (ModelState.IsValid)
{
return Page();
}
else
{
ViewData["Message"] = "Schiefgegangen";
return Page();
}
}