
Google Recaptcha V2/V3 Response Token for Asp.netのサーバー側の検証用ライブラリのためのライブラリ。
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
}
}
}または、Startup getResponsEtokenFromActionArgumentsまたはgetResponseTokenFromexecutedContextのデリゲートで、解析されたデータからトークンを取得する方法を指し示します。
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のスコアしきい値はオプションであり、値をverifyandcheckasync関数に直接渡すことができます。
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" ) ;検証応答のチェックを個別に完了する必要がある場合は、VerifyAndCheckasyncの代わりにVerifyAsyncを使用できます。
var response = await _recaptchaService . VerifyAsync ( credentials . RecaptchaToken ) ;ライブラリは、次の例外を生成できます
| 例外 | 説明 |
|---|---|
| emptyActionException | この例外は、機能で渡されたアクションが空になったときにスローされます。 |
| emptycaptchaanswerexception | この例外は、関数で渡されたCaptchaの回答が空になったときにスローされます。 |
| httprequestexception | この例外は、HTTPリクエストが失敗したときにスローされます。内部例外として補充apiexceptionを保存します。 |
| minscorenotspecifiedException | この例外は、最小スコアが指定されておらず、リクエストがスコア値(V3 Recaptchaを使用)の場合にスローされます。 |
| SecretKeynotspecifedException | この例外は、secretキーがオプションで指定されていないか、パラメーションを要求していない場合にスローされます。 |
| 未知のErrorKeyException | この例外は、検証応答エラーキーが不明の場合にスローされます。 |
これらの例外はすべて、RecaptChaServiceExceptionから継承されます。
例は、ライブラリリポジトリにあります。