Spring Boot starter for Google's reCAPTCHA
Java Groovy
Clone or download
Mariusz Kopylec
Mariusz Kopylec Next release
Latest commit a4b1314 May 29, 2018
Permalink
Failed to load latest commit information.
gradle/wrapper Gradle update Apr 26, 2018
src Test validator fixed May 29, 2018
.gitignore Dependencies update Nov 3, 2017
.travis.yml Travis JDK update Nov 3, 2017
LICENSE Initial commit Nov 20, 2015
README.md Next release May 29, 2018
build.gradle Gradle update Apr 26, 2018
gradlew Dependencies update Nov 3, 2017
gradlew.bat Dependencies update Nov 3, 2017
release Next release May 25, 2017
settings.gradle V2 working, no tests Nov 18, 2015

README.md

reCAPTCHA Spring Boot Starter

Build Status Coverage Status Maven Central

To use the starter you will need a reCAPTCHA site key and a secret key. To get them go to the reCAPTCHA Home Page and set up your reCAPTCHA.

Installing

repositories {
    mavenCentral()
}
dependencies {
    compile group: 'com.github.mkopylec', name: 'recaptcha-spring-boot-starter', version: '2.1.1'
}

How to use

The starter can be used in 3 different modes:

Normal web application usage

Embed reCAPTCHA in HTML web page:

<html>
<head>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    ...
</head>
<body>

<form action="/" method="post">
    <div class="g-recaptcha" data-sitekey="<your_site_key>"></div>
    <input type="submit" value="Validate reCAPTCHA" />
</form>

</body>
</html>

Inject RecaptchaValidator into your controller and validate user reCAPTCHA response:

@Controller
public class MainController {

    @Autowired
    private RecaptchaValidator recaptchaValidator;

    @PostMapping("/")
    public void validateCaptcha(HttpServletRequest request) {
        ValidationResult result = recaptchaValidator.validate(request);
        if (result.isSuccess()) {
            ...
        }
    }
}

Set your secret key in application.yml file:

recaptcha.validation.secret-key: <your_secret_key>
Additional info

RecaptchaValidator provides couple of useful methods to validate reCAPTCHA response.

Spring Security web application usage

Add Spring Security dependency:

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.0.1.RELEASE'
}

Embed reCAPTCHA in HTML login web page:

<html>
<head>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    ...
</head>
<body>

<form action="/login" method="post">
    User: <input name="username" type="text" value="" />
    Password: <input name="password" type="password" value="" />
    <!--<if request has 'showRecaptcha' query param>-->
    <div class="g-recaptcha" data-sitekey="<your_site_key>"></div>
    <!--</if>-->
    <input type="submit" value="Log in" />
</form>

</body>
</html>

Add reCAPTCHA support to your form login security configuration using FormLoginConfigurerEnhancer.

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private FormLoginConfigurerEnhancer enhancer;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        enhancer.addRecaptchaSupport(http.formLogin()).loginPage("/login")
                .and()
                .csrf().disable()
                ...
    }
}

Create custom login failures manager bean by extending LoginFailuresManager:

@Component
public class CustomLoginFailuresManager extends LoginFailuresManager {

    public CustomLoginFailuresManager(RecaptchaProperties recaptcha) {
        super(recaptcha);
    }

    ...
}

Set your secret key in application.yml file:

recaptcha.validation.secret-key: <your_secret_key>
Additional info

After adding reCAPTCHA support to form login configuration you can only add AuthenticationSuccessHandler that extends LoginFailuresClearingHandler and AuthenticationFailureHandler that extends LoginFailuresCountingHandler.

There can be 4 different query parameters in redirect to login page:

  • error - credentials authentication error
  • recaptchaError - reCAPTCHA authentication error
  • showRecaptcha - reCAPTCHA must be displayed on login page
  • logout - user has been successfully logged out

There is a default LoginFailuresManager implementation in the starter which is InMemoryLoginFailuresManager. It is recommended to create your own LoginFailuresManager implementation that persists login failures in some storage.

Integration testing mode usage

Enable testing mode:

recaptcha.testing.enabled: true

Configure testing mode:

recaptcha.testing:
    success-result: false
    result-error-codes: INVALID_SECRET_KEY, INVALID_USER_CAPTCHA_RESPONSE
Additional info

In testing mode no remote reCAPTCHA validation is fired, the validation process is offline.

Configuration properties list

recaptcha:
    validation:
        secret-key: # reCAPTCHA secret key.
        response-parameter: g-recaptcha-response # HTTP request parameter name containing user reCAPTCHA response.
        verification-url: https://www.google.com/recaptcha/api/siteverify # reCAPTCHA validation endpoint.
    security:
        failure-url: /login # URL to redirect to when user authentication fails.
        login-failures-threshold: 5 # Number of allowed login failures before reCAPTCHA must be displayed.
        continue-on-validation-http-error: true # Permits or denies continuing user authentication process after reCAPTCHA validation fails because of HTTP error.
    testing:
        enabled: false # Flag for enabling and disabling testing mode.
        success-result: true # Defines successful or unsuccessful validation result, can be changed during tests.
        result-error-codes: # Errors in validation result, can be changed during tests.

Examples

Go to reCAPTCHA Spring Boot Starter samples to view example applications.

License

reCAPTCHA Spring Boot Starter is published under Apache License 2.0.