Using Google Captcha with Spring Boot Application

Welcome, in this tutorial, we will see how to implement google captcha (reCAPTCHA v2) in a spring boot web application. reCAPTCHA is a free service that protects an application from spammers. It uses advanced risk analysis techniques to keep humans and bots apart.

1. Introduction

Before going further in this tutorial, we will look at the common terminology such as introduction to Spring Boot and Lombok.

1.1 Spring Boot

  • Spring boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or, Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them into the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases
  • It offers a Microservice architecture and cloud configuration that manages all the application related configuration properties in a centralized manner

1.2 Lombok

  • Lombok is nothing but a small library that reduces the amount of boilerplate Java code from the project
  • Automatically generates the getters and setters for the object by using the Lombok annotations
  • Hooks in via the Annotation processor API
  • Raw source code is passed to Lombok for code generation before the Java Compiler continues. Thus, produces properly compiled Java code in conjunction with the Java Compiler
  • Under the target/classes folder you can view the compiled class files
  • Can be used with Maven, Gradle IDE, etc.

1.2.1 Lombok features

valLocal variables are declared as final
varMutable local variables
@Slf4JCreates an SLF4J logger
@CleanupWill call close() on the resource in the finally block
@GetterCreates getter methods for all properties
@SetterCreates setter for all non-final properties
  • Generates implementations of equals(Object other) and hashCode()
  • By default will use all non-static, non-transient properties
  • Can optionally exclude specific properties
  • Generates String of class name, and each field separated by commas
  • Optional parameter to include field names
  • Optional parameter to include a call to the super toString method
  • Generates no-args constructor
  • Will cause compiler error if there are final fields
  • Can optionally force, which will initialize final fields with 0/false/null var – mutable local variables
  • Generates a constructor for all fields that are final or marked @NonNull
  • The constructor will throw a NullPointerException if any @NonNull fields are null val – local variables are declared final
  • Generates a constructor for all properties of the class
  • Any @NotNull properties will have null checks
  • Generates typical boilerplate code for POJOs
  • Combines – @Getter, @Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructor
  • No constructor is generated if constructors have been explicitly declared
  • Implements the Builder pattern for object creation
  • The immutable variant of @Data
  • All fields are made private and final by default

Let us go ahead with the tutorial implementation but before going any further I’m assuming that you’re aware of the Spring boot basics.

2. Using Google Captcha with Spring Boot Application

2.1 Application Pre-requisite

To obtain the API keys we will need a google account. Navigate to the following URL – for the registration of a new site. Enter the details as shown in Fig. 1 and remember to choose the reCAPTCHA v2. Click submit and once the site is successfully registered, the site and client keys will be generated and will be further used in the tutorial.

Google Captcha Spring Boot - Registering a site
Fig. 1: Registering a site

2.2 Tools Used for Spring boot application and Project Structure

We are using Eclipse Kepler SR2, JDK 8, and Maven. In case you’re confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Google Captcha Spring Boot - Project structure
Fig. 2: Project structure

Let us start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application.

3.1 Maven Dependency

Here, we specify the dependency for the Spring boot (Web) and Lombok. Maven will automatically resolve the other dependencies. The updated file will have the following code.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi=""
        <relativePath/> <!-- lookup parent from repository -->
    <description>Springboot and google captcha</description>






3.2 Application properties file

Create a new properties file at the location: SpringbootandGooglecaptcha/src/main/resources/ and add the following code to it. Here we will define the application and google reCAPTCHA configuration.

# application properties
# google recaptcha config properties
# these properties will be used in the class

3.3 Java Classes

Let us write the important java class(es) involved in this application. For brevity, we will skip the following classes –

  • – Custom exception class which will be thrown if the captcha response is invalid
  • – Class to map the attributes of the incoming request
  • – Class to greet the user

3.3.1 Implementation/Main class

Add the following code to the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.


import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// Lombok annotation for logger
// Spring annotation
public class SpringbootandGooglecaptchaApplication {

    public static void main(String[] args) {, args);"Springboot and google captcha application started successfully.");


3.3.2 Captcha response model class

Add the following code to the model class which will be used to map the incoming response from google’s REST API. This class contains –

  • A field called success which will be used to test if the client reCAPTCHA response is valid or not
  • A field called errorCodes to look at the error codes if the client reCAPTCHA response is invalid


import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.time.LocalDateTime;
import java.util.List;

// Lombok annotations
public class CaptchaResponse {

	boolean success;
	LocalDateTime challenge_ts;
	String hostname;
	List<String> errorCodes;

3.3.3 Captcha validator class

Add the following code to the validator class to validate the captcha response coming from the client-side.


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

public class ValidateCaptcha {

	private final RestTemplate template;
	String recaptchaEndpoint;
	String recaptchaSecret;

	public ValidateCaptcha(final RestTemplateBuilder templateBuilder) {
		this.template =;

	// method validate the captcha response coming from the client
	// and return either true or false after the validation.
	// reference url -
	public boolean validateCaptcha(final String captchaResponse) {
		// "captchaResponse" length validation is omitted for brevity."Going to validate the captcha response = {}", captchaResponse);
		final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
		// "secret" is a required param and it represents the shared key between your site 
		// and the recaptcha.
		params.add("secret", recaptchaSecret);
		// "response" is a required param and it represents the user token provided
		// by the recaptcha client-side integration on your site.
		params.add("response", captchaResponse);

		CaptchaResponse apiResponse = null;
		try {
			apiResponse = template.postForObject(recaptchaEndpoint, params, CaptchaResponse.class);
		} catch (final RestClientException e) {
			log.error("Some exception occurred while binding to the recaptcha endpoint.", e);

		if (Objects.nonNull(apiResponse) && apiResponse.isSuccess()) {"Captcha API response = {}", apiResponse.toString());
			return true;
		} else {
			return false;

3.3.4 Controller class

Add the following code to the controller class. The class is injected with the service dependency whose method will be used to validate the incoming captcha response.


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

// Lombok annotation for logger
// Spring annotations
public class HelloCtrl {
	// injected to validate the captcha response coming in the request.
    ValidateCaptcha service;

    // URL - http://localhost:9001/api/welcome
    @ResponseStatus(code = HttpStatus.OK)
    public HelloResponseDto welcome(@RequestBody final HelloDto dto)
            throws ForbiddenException {
        final boolean isValidCaptcha = service.validateCaptcha(dto.getCaptchaResponse());
        if (!isValidCaptcha) {
  "Throwing forbidden exception as the captcha is invalid.");
            throw new ForbiddenException("INVALID_CAPTCHA");

        return new HelloResponseDto("Greetings " + dto.getName());

3.4 Client-side

As the reCAPTCHA cannot be validated via the REST API hence we will need a client code to have it working. Create a new HTML file at the location: SpringbootandGooglecaptcha/src/main/resources/static and add the following code to it.


<html lang="en">
    <title>Springboot and Captcha</title>
    <script src="" type="text/javascript"></script>
    <script src="" type="text/javascript"></script>

<script type="text/javascript">
    function validateAndGetCaptchaResponse() {
        const response = grecaptcha.getResponse();
        return response.length === 0 ? null : response;

    $(document).ready(function () {
        $("#button").click(function () {

            let captchaResponse = validateAndGetCaptchaResponse();
            if (captchaResponse) {
                console.log("Captcha code accepted.")
                let name = $("#name").val();
                let requestObj = {
                    'name': name.length === 0 ? 'Dummy' : name,
                    'captchaResponse': captchaResponse

                    type: "POST",
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(requestObj),
                    url: "http://localhost:9001/api/welcome",
                    success: function (data) {
            } else {
                $("#captcha-error").html("You cannot leave the captcha code empty.");

    <h3>Springboot and Google captcha example</h3>
    <!-- User input -->
    <label for="name">Enter name:</label>
    <input id="name" placeholder="say... Daniel" type="text"/>
    <button id="button" type="submit">Submit</button>

    <div> </div>

    <!-- Google captcha (I'm not robot checkbox) -->
    <!-- SITE_KEY - Represents the site_key generated by the Google reCaptcha service -->
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" id="recaptcha"></div>
    <span id="captcha-error" style="color:red"></span>

4. Run the Application

To execute the application, right-click on the class, Run As -> Java Application.

Google Captcha Spring Boot - Run the Application
Fig. 3: Run the Application

5. Project Demo

When the application is started, navigate to the following URL: http://localhost:9001/ and you’ll see the index page of the application with a reCAPTCHA “I’m not a robot” checkbox as shown in Fig. 4.

Fig. 4: Index page

The HTML code will call our backend endpoint (http://localhost:9001/api/welcome) with a name and captcha-response as the request body. Enter the user details, tick the reCAPTCHA checkbox, and press the button. On successful validation by the backend code, we’ll get a greetings alert.

Fig. 5: Greeting response

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Summary

In this section, you learned,

  • Spring boot and Google reCAPTCHA introduction
  • Steps to register a new site with google reCAPTCHA
  • Steps to implement google reCAPTCHA in Spring Boot

You can download the sample application as an Eclipse project in the Downloads section.

7. Download the Project

This was an example of implementing Google reCAPTCHA in a Spring Boot application.

You can download the full source code of this example here: Using Google Captcha with Spring Boot Application


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
1 year ago

What is “grecaptcha” in client-side, line 11? Where is it from? An object? Is it built-in or imported javascript class object? I want to do similar thing in React.js. I try to do reCapture v.2 for my Spring application when client side is React. I try to add “I’m not a robot” recapture to new users register modal after three fields.

Last edited 1 year ago by Tomas
Back to top button