Library for verifying Google reCAPTCHA v2/v3 response token for ASP.NET Core. The project targets .NET Core 3.1.
Package can be installed using Visual Studio UI (Tools > NuGet Package Manager > Manage NuGet Packages for Solution and search for "Recaptcha.Verify.Net").
Also latest version of package can be installed using Package Manager Console:
PM> Install-Package Recaptcha.Verify.Net
- Add secret key in appsettings.json file
{
"Recaptcha": {
"SecretKey": "<recaptcha secret key>"
}
}
- Configure service in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureRecaptcha(Configuration.GetSection("Recaptcha"));
//...
}
- Use service in controller to verify captcha answer
[ApiController]
[Route("api/[controller]")]
public class LoginController : Controller
{
private readonly ILogger _logger;
private readonly IRecaptchaService _recaptchaService;
public LoginController(ILoggerFactory loggerFactory, IRecaptchaService recaptchaService)
{
_logger = loggerFactory.CreateLogger<LoginController>();
_recaptchaService = recaptchaService;
}
[HttpPost]
public async Task<IActionResult> Login([FromBody] Credentials credentials, CancellationToken cancellationToken)
{
var response = await _recaptchaService.VerifyAsync(
new VerifyRequest()
{
Response = credentials.RecaptchaToken
},
cancellationToken);
if (!response.Success)
{
_logger.LogError($"Recaptcha error: {JsonConvert.SerializeObject(response.ErrorCodes)}");
return BadRequest();
}
// Process login
return Ok();
}
}
Examples could be found in library repository:
- Recaptcha.Verify.Net.ConsoleApp (.NET Core 3.1)
- Recaptcha.Verify.Net.AspNetCoreAngular (ASP.NET Core 3.1 + Angular)