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繼承。
可以在圖書館存儲庫中找到示例: