How To: Use Recaptcha

To use Recaptcha in login form, follow these steps:

Requires Serenity 1.8.5+

You might also use it for another form, but this is just a sample for login.

First, you need to register a new site for Recaptcha at:

https://www.google.com/recaptcha/admin

Once you have your site key, and secret key, enter them in web.config/appSettings section:

  1. <add key="Recaptcha" value="{
  2. SiteKey: '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
  3. SecretKey: '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe' }" />

The keys listed above are only for testing purposes. Never use them in production.

Edit LoginForm.cs to add a Recaptcha property:

  1. public class LoginForm
  2. {
  3. [Placeholder("default username is 'admin'")]
  4. public String Username { get; set; }
  5. [PasswordEditor, Placeholder("default password for admin user is 'serenity'"), Required(true)]
  6. public String Password { get; set; }
  7. [DisplayName(""), Recaptcha]
  8. public string Recaptcha { get; set; }
  9. }

Edit LoginRequest.cs to add a Recaptcha property:

  1. public class LoginRequest : ServiceRequest
  2. {
  3. public string Username { get; set; }
  4. public string Password { get; set; }
  5. public string Recaptcha { get; set; }
  6. }

Edit Login method under AccountPage.cs to validate the captcha server side:

  1. [HttpPost, JsonFilter]
  2. public Result<ServiceResponse> Login(LoginRequest request)
  3. {
  4. return this.ExecuteMethod(() =>
  5. {
  6. request.CheckNotNull();
  7. if (string.IsNullOrEmpty(request.Username))
  8. throw new ArgumentNullException("username");
  9. var username = request.Username;
  10. // just add line below
  11. Serenity.Web.RecaptchaValidation.Validate(request.Recaptcha);
  12. if (WebSecurityHelper.Authenticate(ref username, request.Password, false))
  13. return new ServiceResponse();
  14. throw new ValidationError("AuthenticationError",
  15. Texts.Validation.AuthenticationError);
  16. });
  17. }