Code Monkey home page Code Monkey logo

recaptcha-spring-boot-starter's Introduction

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.2.0'
}

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.4.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.
    timeout:
      connect: 500ms # reCAPTCHA validation request connect timeout.
      read: 1000ms # reCAPTCHA validation request read timeout.
      write: 1000ms # reCAPTCHA validation request write timeout.
  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.

recaptcha-spring-boot-starter's People

Contributors

123haynes avatar ksmith97 avatar mkopylec avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.