
Google Recaptcha V2/V3 응답 토큰의 서버 측 확인을위한 라이브러리 ASP.NET.
버전 2.0.0에서 시작하는 recaptcha.verify.net 다음 플랫폼과 2.0에서 .NET 표준을 지원하는 대상을 지원합니다.
비주얼 스튜디오 UI (Tools> 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 또는 getResponsEtokenFomeXecutingContext Delegate에서 설정하여 구문 분석 데이터에서 토큰을 얻는 방법을 지적합니다.
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 요청이 실패하면 발생합니다. 내부 예외로 refit.apiexception을 저장합니다. |
| minscorenotspecifiedException | 이 예외는 최소 점수가 지정되지 않았고 요청에 점수 값 (중고 V3 Recaptcha)이있었습니다. |
| SecretKeynotspecifiedException | 이 예외는 옵션이나 요청 매개 변수에 Secret Key가 지정되지 않았을 때 발생합니다. |
| unknownerrorkeyException | 이 예외는 확인 응답 오류 키가 알 수 없을 때 발생합니다. |
이러한 모든 예외는 RecaptchaserviceException에서 상속됩니다.
예제는 라이브러리 저장소에서 찾을 수 있습니다.