Spring Boot starter for Google's reCAPTCHA v3.
repositories {
mavenCentral()
}
dependencies {
implementation("com.michael-bull.spring-boot-starter-recaptcha:spring-boot-starter-recaptcha:1.0.4")
}
Register your application on the key registration page.
recaptcha.keys:
site: "<your site key>"
secret: "<your secret key>"
class RegisterForm {
var recaptchaAction: String? = "register"
var recaptchaResponseToken: String? = null
@Email
var email: String? = null
}
@Component
@RequestScope
class RegisterFormValidator @Inject constructor(
private val request: HttpServletRequest,
private val recaptchaValidator: RecaptchaValidator
) : Validator {
override fun supports(clazz: Class<*>): Boolean {
return RegisterForm::class.java.isAssignableFrom(clazz)
}
override fun validate(target: Any, errors: Errors) {
val form = target as RecoverAccountForm
val action = form.recaptchaAction
val responseToken = form.recaptchaResponseToken
recaptchaValidator
.validate("recaptchaResponseToken", request, action, responseToken, errors)
.onSuccess { (_, response) -> checkResponse(response, errors) }
}
private fun checkResponse(response: SiteVerifyResponse, errors: Errors) {
val score = response.score
if (score != null && score < 0.2) {
errors.rejectValue("recaptchaResponseToken", "Score too low")
}
}
}
@Controller
class RegisterController @Inject constructor(
private val formValidator: RegisterFormValidator
) {
@InitBinder("form")
fun initFormBinder(binder: WebDataBinder) {
binder.addValidators(formValidator)
}
/* get and post handlers... */
}
Error codes generated by the RecaptchaValidator can be internationalized by
adding the following entries to your messages.properties
:
captcha.error.actionMissing=Captcha action missing.
captcha.error.incomplete=Captcha incomplete.
captcha.error.request=Failed to submit captcha.
captcha.error.responseMissing=No response from captcha service.
captcha.error.response=Error response from captcha service.
captcha.error.failed=Captcha failed. Please try again.
captcha.error.actionMismatch=Captcha action mismatch.
Bug reports and pull requests are welcome on GitHub.
This project is available under the terms of the ISC license. See the
LICENSE
file for the copyright information and licensing terms.