
مكتبة للتحقق من جانب الخادم من Google Recaptcha V2/V3 Response لـ ASP.NET.
recaptcha.verify.net بدءًا من الإصدار 2.0.0 يدعم المنصات التالية وأي هدف يدعم .NET Standard من 2.0:
يمكن تثبيت الحزمة باستخدام Visual Studio UI (أدوات> Nuget Package Manager> إدارة حزم nuget للحل والبحث عن "recaptcha.verify.net").
كما يمكن تثبيت أحدث إصدار من الحزمة باستخدام وحدة التحكم في Package Manager:
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
}
}
}أو تم تعيينه في بدء التشغيل GetResPonseSetOkenFromActionActionActions أو getResponseSetokenFromexecutingContext الذي يشير إلى كيفية الحصول على رمز من البيانات المحلية.
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" ) ;إذا كان من الضروري إكمال التحقق من استجابة التحقق بشكل منفصل ، فيمكنك استخدام VerifyAsync بدلاً من VerifyandCheckAsync.
var response = await _recaptchaService . VerifyAsync ( credentials . RecaptchaToken ) ;يمكن أن تنتج المكتبة استثناءات التالية
| استثناء | وصف |
|---|---|
| الفراغ | يتم طرح هذا الاستثناء عندما يكون الإجراء الذي تم تمريره في الوظيفة فارغًا. |
| regalcaptchaanswerexception | يتم إلقاء هذا الاستثناء عندما يتم تمرير إجابة Captcha في الوظيفة. |
| httprequestexception | يتم طرح هذا الاستثناء عند فشل طلب HTTP. المتاجر refit.apiexception كاستثناء داخلي. |
| minscorenotspecifiedException | يتم إلقاء هذا الاستثناء عندما لم يتم تحديد الحد الأدنى من النتيجة وأن الطلب كان له قيمة النتيجة (المستخدمة V3 recaptcha). |
| SecretKeynotspecifiedException | يتم إلقاء هذا الاستثناء عندما لم يتم تحديد المفتاح السري في الخيارات أو طلب المعاملات. |
| UnknownerRorKeexception | يتم طرح هذا الاستثناء عندما يكون مفتاح خطأ استجابة التحقق غير معروف. |
كل هذه الاستثناءات ورثت من RecaptChaserviceException.
يمكن العثور على أمثلة في مستودع المكتبة: