Recaptcha.Verify.Net
1.2.0
See the version list below for details.
dotnet add package Recaptcha.Verify.Net --version 1.2.0
NuGet\Install-Package Recaptcha.Verify.Net -Version 1.2.0
<PackageReference Include="Recaptcha.Verify.Net" Version="1.2.0" />
paket add Recaptcha.Verify.Net --version 1.2.0
#r "nuget: Recaptcha.Verify.Net, 1.2.0"
// Install Recaptcha.Verify.Net as a Cake Addin
#addin nuget:?package=Recaptcha.Verify.Net&version=1.2.0
// Install Recaptcha.Verify.Net as a Cake Tool
#tool nuget:?package=Recaptcha.Verify.Net&version=1.2.0
Recaptcha.Verify.Net
Library for server-side verification of Google reCAPTCHA v2/v3 response token for ASP.NET Core 3.1+.
Installation
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
Using reCAPTCHA verification
- Add secret key in appsettings.json file.
{
"Recaptcha": {
"SecretKey": "<recaptcha secret key>",
"ScoreThreshold": 0.5
}
}
- Configure service in Startup.cs.
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureRecaptcha(Configuration.GetSection("Recaptcha"));
//...
}
- Use service in controller to verify captcha answer and check response action and score (score for V3).
[ApiController]
[Route("api/[controller]")]
public class LoginController : Controller
{
private const string _loginAction = "login";
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 checkResult = await _recaptchaService.VerifyAndCheckAsync(
credentials.RecaptchaToken,
_loginAction,
cancellationToken);
if (!checkResult.Success)
{
if (!checkResult.ScoreSatisfies)
{
// Handle score less than specified threshold for v3
return BadRequest();
}
if (!checkResult.Response.Success)
{
// Handle unsuccessful verification response
_logger.LogError($"Recaptcha error: {JsonConvert.SerializeObject(checkResult.Response.ErrorCodes)}");
}
// Unsuccessful verification and check
return BadRequest();
}
// Process login
return Ok();
}
}
Using attribute for reCAPTCHA verification
- Specify in appsettings.json name of parameter for a way in which reCAPTCHA response token is passed.
{
"Recaptcha": {
...
"RecaptchaAttributeOptions": {
"ResponseTokenNameInHeader": "RecaptchaTokenInHeader", // If token is passed in header
"ResponseTokenNameInQuery": "RecaptchaTokenInQuery", // If token is passed in query
"ResponseTokenNameInForm": "RecaptchaTokenInForm" // If token is passed in form
}
}
}
Or set in Startup GetResponseTokenFromActionArguments or GetResponseTokenFromExecutingContext delegate that points how to get token from parsed data.
services.ConfigureRecaptcha(Configuration.GetSection("Recaptcha"),
// Specify how to get token from parsed arguments for using in RecaptchaAttribute
o => o.RecaptchaAttributeOptions.GetResponseTokenFromActionArguments =
d =>
{
if (d.TryGetValue("credentials", out var credentials))
{
return ((BaseRecaptchaCredentials)credentials).RecaptchaToken;
}
return null;
});
Credentials model used in example has base class with property containing token.
public class BaseRecaptchaCredentials
{
public string RecaptchaToken { get; set; }
}
public class Credentials : BaseRecaptchaCredentials
{
public string Login { get; set; }
public string Password { get; set; }
}
- Add Recaptcha attribute in controller to verify captcha answer and check response action and score (score for V3).
[Recaptcha("login")]
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] Credentials credentials, CancellationToken cancellationToken)
{
// Process login
return Ok();
}
Directly passing score threshold
Score threshold in appsettings.json is optional and value could be passed directly into VerifyAndCheckAsync function.
var scoreThreshold = 0.5f;
var checkResult = await _recaptchaService.VerifyAndCheckAsync(
credentials.RecaptchaToken,
_loginAction,
scoreThreshold);
Using score threshold map
Based on the score, you can take variable action in the context of your site instead of blocking traffic to better protect your site. Score thresholds specified for actions allow you to achieve adaptive risk analysis and protection based on the context of the action.
- Specify ActionsScoreThresholds in appsettings.json. If specified ScoreThreshold value will be used as default score threshold for actions that are not in map.
{
"Recaptcha": {
"SecretKey": "<recaptcha secret key>",
"ScoreThreshold": 0.5,
"ActionsScoreThresholds": {
"login": 0.75,
"test": 0.9
}
}
}
- Call VerifyAndCheckAsync function
// Response will be checked with score threshold equal to 0.75
var checkResultLogin = await _recaptchaService.VerifyAndCheckAsync(credentials.RecaptchaToken, "login");
// Response will be checked with score threshold equal to 0.9
var checkResultTest = await _recaptchaService.VerifyAndCheckAsync(credentials.RecaptchaToken, "test");
// Response will be checked with score threshold equal to 0.5
var checkResultSignUp = await _recaptchaService.VerifyAndCheckAsync(credentials.RecaptchaToken, "signup");
Process verify request without checking action and score from response
If checking of verification response needs to be completed separately then you can use VerifyAsync insted of VerifyAndCheckAsync.
var response = await _recaptchaService.VerifyAsync(credentials.RecaptchaToken);
Handling exceptions
Library can produce following exceptions Exception | Description --- | --- EmptyCaptchaAnswerException | This exception is thrown when captcha answer passed in function is empty. HttpRequestException | This exception is thrown when http request failed. Stores Refit.ApiException as inner exception. MinScoreNotSpecifiedException | This exception is thrown when minimal score was not specified and request had score value (used V3 reCAPTCHA). SecretKeyNotSpecifiedException | This exception is thrown when secret key was not specified in options or request params. UnknownErrorKeyException | This exception is thrown when verification response error key is unknown.
All of these exceptions are inherited from RecaptchaServiceException.
Examples
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)
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp3.1 is compatible. |
-
.NETCoreApp 3.1
- Microsoft.AspNetCore.Mvc.Core (>= 2.2.5)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 5.0.0)
- Microsoft.Extensions.Options (>= 5.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 5.0.0)
- Newtonsoft.Json (>= 13.0.1)
- Refit (>= 6.2.16)
- Refit.HttpClientFactory (>= 6.2.16)
- Refit.Newtonsoft.Json (>= 6.2.16)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.