I implemented Recaptcha in my main ASP.NET applications. In my account:
@if (Model.RecaptchaSiteKey.Length > 0) { <script src='https://www.google.com/recaptcha/api.js'></script> } @if (Model.RecaptchaSiteKey.Length > 0) { <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="g-recaptcha" data-sitekey="@Model.RecaptchaSiteKey"></div> @Html.ValidationMessage("recaptchaerror", new { @class = "text-danger" }) </div> </div> }
I implemented the extension method on the controller so that I can easily check the captcha server side from any controller where I use it.
public static async Task<RecaptchaResponse> ValidateRecaptcha( this Controller controller, HttpRequest request, string secretKey) { var response = request.Form["g-recaptcha-response"]; var client = new HttpClient(); string result = await client.GetStringAsync( string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response) ); var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(result); return captchaResponse; }
Then this snippet from the login method in my AccountController checks the server side of the captcha using this extension method:
if ((Site.CaptchaOnLogin) && (Site.RecaptchaPublicKey.Length > 0)) { var recpatchaSecretKey = Site.RecaptchaPrivateKey; var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey); if (!captchaResponse.Success) { ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again"); return View(model); } }
Note that you must use this keyword to call extension methods on the controller.
I am using this in several projects now, so if you need to see more code, the simplest thing in my project is SimpleAuth , but I also use cloudscribe it
source share