Using Google reCaptcha with Spring Boot application


reCaptcha by Google is a library used to prevent bots from submitting data to your public forms or accessing your public data.

In this post, we will look at how to integrate reCaptcha with a Spring Boot based web application

Setting up reCaptcha

You should create an API key from admin panel. You have to create a sample app as shown below:


Post that you should be able to see the key and secret and few instructions which are good enough to get started as shown below:


Creating Sample Spring Boot App

As usual navigate to and fill up as shown below and download the project:

Open in your favorite IDE and then run the RecaptchaDemoApplication and access the app from http://localhost:8080. As there are no controllers defined you will see an error.

Creating a Public Page With a Form

We will make use of:

The HTML for the form with reCaptcha enabled is:

    <form id="signup-form" class="form-horizontal" method="POST" 
      th:action="@{/api/signup}" th:object="${user}">
      <div class="form-group">
        <label class="control-label required">First Name</label>
        <input type="text" th:field="*{firstName}" 
          class="form-control required" />
      <div class="form-group">
        <label class="control-label required">Last Name</label>
        <input type="text" th:field="*{lastName}" 
          class="form-control required" />
      <div class="form-group">
        <label class="control-label required">Email</label>
        <input type="text" th:field="*{email}" 
          class="form-control required" />
      <div class="form-group">
        <label class="control-label required">Password</label>
        <input type="password" th:field="*{password}" 
          class="form-control required" />
      <div class="form-group">
        <label class="control-label required">Confirm Password</label>
        <input type="password" th:field="*{confirmPassword}" 
          class="form-control required" />
      <div class="g-recaptcha" 
      <button type="submit" class="btn btn-primary">Submit</button>

The important piece in the above for is the div with g-recaptcha class which has the public site key. The other secret key should be secure in your server using which you validate the captcha from Google server. Also, make sure the reCaptcha JS is just before the “.

Loading the URL http://localhost:8080/ renders the form:


Creating the API for Form Handling

Next up is to verify the captcha while processing the add user API. Google provides an endpoint to which we will POST to verify the captcha. Below is the code which verifies the captcha:

public class RecaptchaService {

  String recaptchaSecret;
  private static final String GOOGLE_RECAPTCHA_VERIFY_URL =
  RestTemplateBuilder restTemplateBuilder;

  public String verifyRecaptcha(String ip, 
    String recaptchaResponse){
    Map<String, String> body = new HashMap<>();
    body.put("secret", recaptchaSecret);
    body.put("response", recaptchaResponse);
    body.put("remoteip", ip);
    log.debug("Request body for recaptcha: {}", body);
    ResponseEntity<Map> recaptchaResponseEntity =
          body, Map.class, body);
    log.debug("Response from recaptcha: {}", 
    Map<String, Object> responseBody = 
    boolean recaptchaSucess = (Boolean)responseBody.get("success");
    if ( !recaptchaSucess) {
      List<String> errorCodes = 
      String errorMessage =
          .map(s -> RecaptchaUtil.RECAPTCHA_ERROR_CODE.get(s))
          .collect(Collectors.joining(", "));
      return errorMessage;
    }else {
      return StringUtils.EMPTY;

We have created a map which maps the response code with the response message provided by Google as shown below:

public class RecaptchaUtil {

  public static final Map<String, String> 
    RECAPTCHA_ERROR_CODE = new HashMap<>();

  static {
        "The secret parameter is missing");
        "The secret parameter is invalid or malformed");
        "The response parameter is missing");
        "The response parameter is invalid or malformed");
        "The request is invalid or malformed");

Let us use the RecaptchaService in the form api as shown below:

public ResponseEntity<?> signup(@Valid User user, 
  @RequestParam(name="g-recaptcha-response") String recaptchaResponse,
  HttpServletRequest request

  String ip = request.getRemoteAddr();
  String captchaVerifyMessage = 
      captchaService.verifyRecaptcha(ip, recaptchaResponse);

  if ( StringUtils.isNotEmpty(captchaVerifyMessage)) {
    Map<String, Object> response = new HashMap<>();
    response.put("message", captchaVerifyMessage);
    return ResponseEntity.badRequest()
  return ResponseEntity.ok().build();

The captcha on the UI is passed in the response as a request param with key g-recaptcha-response. So we invoke the captcha verify service with this response key and the option ip address. The result of the verification is either a success or a failure. We capture the message if its is failure and return it to the client.

The complete code for this sample can be found here.

1 thought on “Using Google reCaptcha with Spring Boot application”

Leave a Reply