Recaptcha.Verify.Net
v2.3.0

用于服务器端验证Google recaptcha v2/v3响应的库库。
recaptcha.verify.net从版本2.0.0开始支持以下平台和任何支持2.0的NET标准的目标:
可以使用Visual Studio UI(工具> Nuget软件包管理器>管理Nuget软件包来解决方案,并搜索“ recaptcha.verify.net”)。
此外,可以使用软件包管理器控制台安装最新版本的软件包:
PM> Install-Package Recaptcha.Verify.Net
{
"Recaptcha" : {
"SecretKey" : " <recaptcha secret key> " ,
"ScoreThreshold" : 0.5
}
} public void ConfigureServices ( IServiceCollection services )
{
services . AddRecaptcha ( Configuration . GetSection ( "Recaptcha" ) ) ;
//...
} [ 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 . Response . Success )
{
// Handle unsuccessful verification response
_logger . LogError ( "Recaptcha error: {errorCodes}" , JsonConvert . SerializeObject ( checkResult . Response . ErrorCodes ) ) ;
}
if ( ! checkResult . ScoreSatisfies )
{
// Handle score less than specified threshold for v3
}
// Unsuccessful verification and check
return BadRequest ( ) ;
}
// Process login
return Ok ( ) ;
}
}{
"Recaptcha" : {
...
"AttributeOptions" : {
"ResponseTokenNameInHeader" : " RecaptchaTokenInHeader " , // If token is passed in header
"ResponseTokenNameInQuery" : " RecaptchaTokenInQuery " , // If token is passed in query
"ResponseTokenNameInForm" : " RecaptchaTokenInForm " // If token is passed in form
}
}
}或在启动getResponseTokenFromactionArguments或getResponseTokenFromeXecutingContext委托中设置,该委托指出了如何从解析数据中获取令牌。
services . AddRecaptcha ( Configuration . GetSection ( "Recaptcha" ) ,
// Specify how to get token from parsed arguments for using in RecaptchaAttribute
o => o . AttributeOptions . GetResponseTokenFromActionArguments =
d =>
{
if ( d . TryGetValue ( "credentials" , out var credentials ) )
{
return ( ( BaseRecaptchaCredentials ) credentials ) . RecaptchaToken ;
}
return null ;
} ) ;示例中使用的凭据模型具有包含令牌的属性的基类。
public class BaseRecaptchaCredentials
{
public string RecaptchaToken { get ; set ; }
}
public class Credentials : BaseRecaptchaCredentials
{
public string Login { get ; set ; }
public string Password { get ; set ; }
} [ Recaptcha ( "login" ) ]
[ HttpPost ( "Login" ) ]
public async Task < IActionResult > Login ( [ FromBody ] Credentials credentials , CancellationToken cancellationToken )
{
// Process login
return Ok ( ) ;
}appSettings.json中的得分阈值是可选的,并且可以将值直接传递到验证界面函数中。
var scoreThreshold = 0.5f ;
var checkResult = await _recaptchaService . VerifyAndCheckAsync (
credentials . RecaptchaToken ,
_loginAction ,
scoreThreshold ) ;根据分数,您可以在网站的上下文中采取可变操作,而不是阻止流量以更好地保护您的网站。为操作指定的分数阈值使您可以根据动作的背景来实现自适应风险分析和保护。
{
"Recaptcha" : {
"SecretKey" : " <recaptcha secret key> " ,
"ScoreThreshold" : 0.5 ,
"ActionsScoreThresholds" : {
"login" : 0.75 ,
"test" : 0.9
}
}
} // 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" ) ;如果需要单独完成验证响应的检查,则可以使用verifyasyanc而不是verifyAndyandCheckEckAsync。
var response = await _recaptchaService . VerifyAsync ( credentials . RecaptchaToken ) ;图书馆可以产生以下例外
| 例外 | 描述 |
|---|---|
| emptyActionException | 当通过功能中传递的操作为空时,将抛出此例外。 |
| 空captchaanswerexception | 当通过功能中传递的验证码答案为空时,会抛出此例外。 |
| httprequestexception | 当HTTP请求失败时,会抛出此例外。存储重新安装。 |
| MinScoreNotsPecifiedException | 当未指定最小分数并且请求具有得分值(使用的v3 recaptcha)时,会抛出此例外。 |
| SecretKeyNotsPecifiedException | 当未在选项或请求参数中指定秘密密钥时,会抛出此异常。 |
| 不知名的ErkeyException | 当验证响应错误键未知时,会抛出此异常。 |
所有这些异常均从recaptchaserviceException继承。
可以在图书馆存储库中找到示例: