You are here
Home > Spring Boot >

How To Secure Spring Boot Application By Google reCAPTCHA?

How To Secure Spring Boot Application By Google reCAPTCHA?In continuation to previous article on Securing Spring Boot Application by Simple CAPTCHA, here in this article we will discuss about Google reCAPTCHA. Needless to say, reCAPTCHA protects your application or website from fraud and misuse. It uses an advanced risk analysis engine and flexible challenges to keep malicious software out from entering into offensive activities on your website. Meanwhile, allowed users will be able to login, view pages, or create accounts. On the other hand, fraud users will be blocked.

We have already discussed the fundamentals of captcha including it’s definition & types in our previous article. In short, reCAPCHA is a type of captcha security. We will talk all about it in our article ‘How To Secure Spring Boot Application By Google reCAPTCHA?’.

You can block automated software such as bots once you add reCAPTCHA to your application. On the other hand, you can allow your legal users to enter with ease. In the process of reCAPTCHA validation, If you see a green checkmark, You’ve passed the robot test. Then you can carry on with the next step what you were doing. Of course, it’s that easy. Sometimes, it needs some extra info from you to make sure you’re human and not a robot. Then, it asks you to figure out a challenge such as solving the matching images puzzle. Now let’s discuss our topic ‘How To Secure Spring Boot Application By Google reCAPTCHA?’.

What Can You Expect from This Article?

Once you complete going through this article, you will be able to answer :

1) What is Google reCAPTCHA?

2) Why did we need Google reCAPTCHA?

3) Then How to implement Google reCAPTCHA in your application?

4) How to register your Application to Google reCAPTCHA v2?

5) Additionally, What are the different configurations provided by Google as reCaptcha API?

6) How to implement a Google reCAPTCHA validation in a Spring Boot application?

7) How to create a Registration form using Spring Boot MVC concept?

8) How to create a industry Standard Spring Boot MVC application using all layers?

9) How to apply bootstrap design in a form creation?

10) How to test a Google reCAPTCHA integrated application?

11) Last but not the least ‘How To Secure Spring Boot Application By Google reCAPTCHA?’

What is Google reCAPTCHA?

Google reCAPTCHA is nothing, but a CAPTCHA system owned by Google. It is a system that allows web hosts to distinguish between human and automated access to applications or websites. We also call it ‘No CAPTCHA reCAPTCHA‘ and this is how it looks. Using this new API on websites, users will be able to securely and easily verify that they’re human without actually having to solve a CAPTCHA. Instead, they will confirm that they are not a robot with just a single click.

How to implement Google reCAPTCHA in your application?

First of all you need to register your application in Google Captcha admin console. Then Google will tell you what & how to configure in your code. In fact, Google will provide you step by step guidance to get reCAPTCHA features in your application. However, we will provide you enough details to get your implementation done. To illustrate it, we will create a User Registration Form. Then we will apply the captcha specific configurations in our code provided by Google.

How To Secure Spring Boot Application By Google reCAPTCHA?

How to register your Application to Google reCAPTCHA v2?

In order to register your application for captcha verification, you have to visit Google reCaptcha website. Follow the steps given below.

Step#1 : Login with your Gmail account & Go to https://www.google.com/recaptcha/about/ and click on ‘Admin Console’
or hit the link https://www.google.com/recaptcha/admin/create directly on your Browser.

Step#2 : Fill the label name as per your choice.

Step#3 : Select reCAPTCHA v2 and then select “I’m not a robot” checkbox.

Step#4 : In the Domains field type ‘localhost’ for now. You can also type comma separated multiple domains.

Step#5 : Select checkbox ‘Accept the reCAPTCHA Terms of Service’ and then submit.

Step#6 : Once clicked on ‘submit’ button, a new page with site key and secret key will appear. These keys are for client side & server side integration respectively.

Now you have to utilize these keys in your application. You have to integrate client side key if you are using UI such as HTML, Thymeleaf, JSP, Angular etc. Likewise server side key is for your server side programming such as Servlet, Spring MVC, Spring Boot etc.

Adding reCAPTCHA to your site

The new page after clicking on submit button will look like below screen.

How To Secure Spring Boot Application By Google reCAPTCHA?

The SITE KEY will be inserted at ‘div’ tag in your html as below.

<div class="g-recaptcha" data-sitekey="your_site_key"></div>

The SECRET KEY will be used as parameter in URL as below.

https://www.google.com/recaptcha/api/siteverify?secret=your_secret_key

Subsequently, when you click on ‘see client side integration’ link, a new page just like below will appear.

reCAPTCHA

Observe the highlighted part in the above page. You have to insert these two tags in your html file at UI level.

Equally important, when you click on ‘see server side integration’ link, a new page like below will appear.

reCAPTCHA

Here in this page we need to keep attention on the highlighted parts. Check below code snippet to get idea on where to integrate them in our code.

How To Secure Spring Boot Application By Google reCAPTCHA?

Further you will find complete code in below section.

How To Secure Spring Boot Application By Google reCAPTCHA?

In this section we will implement Google reCAPTCHA completely. Let’s start with creating a USER Registration Form and then apply code configurations provided by Google in it. If user validates reCAPTCHA successfully, the registration process will proceed accordingly. On successful registration a page with list of all users will appear. We will do the whole implementation step by step.

What all Tools & Technologies used in this example project?

♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
⇒ Dependent Starters : Spring Web, Thymeleaf, Spring Data JPA, H2 Database, Lombok, Spring Boot DevTools
♦ JDK8 or later versions (Extremely tested on JDK8, JDK11 and JDK14)

Step#1: Creating Spring Boot Project using STS

While creating Starter Project select ‘Spring Web’, ‘Thymeleaf’, ‘Spring Data JPA’, ‘H2 Database’, ‘Lombok’ and ‘Spring Boot DevTools’ as starter project dependencies. Even If you don’t know how to create Spring Boot Starter Project, Kindly visit Internal Link. Also, if you want to know more about Lombok, then visit a separate article on ‘Lombok‘.

Step#2 : Update database properties in application.properties file

Update application.properties to connect with H2 Database accordingly. Please note that we are using H2 in-memory database here. However You can use any other DB as per your convenience. The file will look like as below code.

#application.properties
---------------------------------------------
#server.port=8080
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:recaptchadb

Step#3 : Create User Entity & Repository interface

Now create User.java & UserRepositoty.java as below.

User.java
package com.dev.springboot.recaptcha.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import lombok.Data;

@Data
@Entity
public class User {

@Id
@GeneratedValue
private Integer id;
private String name;
private String email;


}
UserRepository.java
package com.dev.springboot.recaptcha.repo;

import org.springframework.data.jpa.repository.JpaRepository;

import com.dev.springboot.recaptcha.model.User;

public interface UserRepository extends JpaRepository<User, Integer>{

}

Step#4 : Create Service Interface & Service Implementation class

Create Service Interface and Service Impl class as IUserService.java and UserServiceImpl.java accordingly as shown below.

IUserService.java
package com.dev.springboot.recaptcha.service;

import java.util.List;

import com.dev.springboot.recaptcha.model.User;

public interface IUserService {

Integer createUser(User user);
List<User> getAllUsers();
}
UserServiceImpl.java
package com.dev.springboot.recaptcha.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dev.springboot.recaptcha.model.User;
import com.dev.springboot.recaptcha.repo.UserRepository;

@Service
public class UserServiceImpl implements IUserService {

@Autowired
private UserRepository repo;

@Override
public Integer createUser(User user) {
Integer userId= repo.save(user).getId();
return userId;
}

@Override
public List<User> getAllUsers() {
List<User> users= repo.findAll();
return users;
}

}

Step#5 : Create a model class to receive Captcha Response

Create a model class with three mandatory fields as below. It will help in capturing captcha response.

CaptchaResponse.java
package com.dev.springboot.recaptcha.model;

import lombok.Data;

@Data
public class CaptchaResponse {

private boolean success;
private String challenge_ts;
private String hostname;
}

Step#6 : Create AppConfig class to create RestTemplate

It is just to create RestTemplate object. Further we will need a Rest Consumer call in the next Validator class.

AppConfig.java
package com.dev.springboot.recaptcha.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

Step#7 : Create CaptchaValidator class to validate reCAPTCHA

This class is to check whether reCAPTCHA validated successfully or not. It will have one isValidCaptcha() method. In this we will make a rest consumer call to get response. This class has major configurations provided by Google. Kindly observe URL and its parameters.

CaptchaValidator.java
package com.dev.springboot.recaptcha.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.dev.springboot.recaptcha.model.CaptchaResponse;

@Component
public class CaptchaValidator {

@Autowired
private RestTemplate restTemplate;

public boolean isValidCaptcha(String captcha) {

String url= "https://www.google.com/recaptcha/api/siteverify";
String params="?secret=6LfisjsaAAAAAF8ZsWeSH3YPrWnzFTCSaQIodQ6J&response="+captcha;
String completeUrl=url+params;
CaptchaResponse resp= restTemplate.postForObject(completeUrl, null, CaptchaResponse.class);
return resp.isSuccess();
}
}

Step#8 : Create UserController class 

Next, write a controller class for User as ‘UserController.java’. It will control the complete user registration page. In saveUser() method we have validation logic. If isValidCaptcha() returns true then save form data to database. If not, go back to registration form with some message such as ‘retry for captcha validation’.

UserController.java
package com.dev.springboot.recaptcha;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.dev.springboot.recaptcha.model.User;
import com.dev.springboot.recaptcha.service.IUserService;
import com.dev.springboot.recaptcha.validator.CaptchaValidator;

@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private IUserService service;
@Autowired
private CaptchaValidator validator;

@GetMapping("/register")
public String registerUser(Model model) {
model.addAttribute("user", new User());
return "registerUser";
}

@PostMapping("/save")
public String saveUser(
@ModelAttribute User user,
Model model,
@RequestParam("g-recaptcha-response") String captcha
) {
if(validator.isValidCaptcha(captcha)) {
Integer id = service.createUser(user);
model.addAttribute("message", "User with id : '"+id+"' Saved Successfully !");
model.addAttribute("user", new User());
} else{
model.addAttribute("message", "Please validate captcha first");
}

return "registerUser";
}

@GetMapping("/all")
public String getAllUsers(Model model) {
List<User> users= service.getAllUsers();
model.addAttribute("list", users);
return "listUsers";
}

}

Step#9 : Write UI pages(Thymeleaf) 

Below are the .html files for UI pages. We have only two pages registerUser.html and listUsers.html. Now place these pages inside ‘src/main/resources/templates’ folder accordingly. Moreover we have also used bootstrap for page designing. Please keep in mind that registerUser.html page will have two tags provided by Google.

registerUser.html
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container p-3 my-3 border">
<div class="card-header bg-info text-black">
<h3>USER REGISTRATION</h3>
</div>
<div class="card-body">
<form th:action="@{/user/save}" method="POST" th:object="${user}">
<div class="row">
<div class="col-2">NAME</div>
<div class="col-4">
<input type="text" th:field="*{name}" class="form-control"/>
</div>
</div>
<br/>
<div class="row">
<div class="col-2">EMAIL</div>
<div class="col-4">
<input type="text" th:field="*{email}" class="form-control"/>
</div>
</div>
<br/>
<div class="row">
<div class="col-2"> Validate reCAPTCHA</div>
<div class="col-4">
<div class="g-recaptcha" data-sitekey="6LfisjsaAAAAALj_vfahHXuAWRjjTN416bgVuuUM"></div>
</div>
</div>

<br/>
<input type="submit" value="Register" class="btn btn-success"/>
<a th:href="@{/user/all}" class="btn btn-info">View All Users</a>
</form>
</div>
<div class="card-footer bg-info text-black">
<span th:text="${message}"></span>
</div>
</div>

</body>
</html>
listUsers.html
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
</head>
<body>
<div class="container p-3 my-3 border">
<div class="card-header bg-info text-black">
<h3>USER LIST</h3>
</div>
<div class="card-body">
<table class="table table-hover">
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
</tr>
<tr th:each="ob:${list}">
<td th:text="${ob.id}"></td>
<td th:text="${ob.name}"></td>
<td th:text="${ob.email}"></td>
</tr>
</table>
</div>
<br/>
<a th:href="@{/user/register}" class="btn btn-success">Add User</a>
</div>
</body>
</html>

How to test the application?

1) Start the application : Right click on the project, then select “Run As’ >> ‘Spring Boot App’.

2) Now enter the registration page URL http://localhost:8080/user/register into the browser.

3) Fill up the values in the fields. Then validate captcha by clicking on checkbox. If image puzzle appears solve it accordingly. Now click on the ‘Register’ button accordingly.

4) If you validate captcha correctly, you will see the successful message at the form footer. Now click on the ‘View All users’ button. You will see the details of the registered users. Further to register other user you can click on ‘ADD USER’ button.

5) In contrast, If you don’t validate the captcha correctly, you will not be able to register. Instead you will get ‘Please validate captcha first’ message at the footer of the form.

reCaptcha

How to verify the registered users in H2 DB?

1) In order to see H2-DB console, type http://localhost:8080/h2-console/ into the new browser window

2) Then enter JDBC URL value as ‘jdbc:h2:mem:recaptchadb

3) Now click on ‘connect’ button.

4) Finally run a query ‘select * from user’. You will get the expected results.

♥ Please note that this is an in-memory DB. Therefore values will persist into DB till the session is valid.

Conclusion

After going through all the theoretical and example part of ‘How To Secure Spring Boot Application By Google reCAPTCHA?’, finally, we are able to implement Google reCAPTCHA security in a Spring Boot project. Similarly, we expect from you to further extend these examples. Also try to implement them in your project accordingly. In addition, If there is any update in future, we will also update this article accordingly. Moreover, Feel free to provide your comments in comments section below.

2 thoughts on “How To Secure Spring Boot Application By Google reCAPTCHA?

Leave a Reply


Top