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. But 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?’.
Table of Contents (Click on links below to navigate)
- 1 What Can You Expect from This Article?
- 2 What is Google reCAPTCHA?
- 3 How to implement Google reCAPTCHA in your application?
- 4 How to register your Application to Google reCAPTCHA v2?
- 5 How To Secure Spring Boot Application By Google reCAPTCHA?
- 5.1 What all Tools & Technologies used in this example project?
- 5.2 Step#1: Creating Spring Boot Project using STS
- 5.3 Step#2 : Update database properties in application.properties file
- 5.4 Step#3 : Create User Entity & Repository interface
- 5.5 Step#4 : Create Service Interface & Service Implementation class
- 5.6 Step#5 : Create a model class to receive Captcha Response
- 5.7 Step#6 : Create AppConfig class to create RestTemplate
- 5.8 Step#7 : Create CaptchaValidator class to validate reCAPTCHA
- 5.9 Step#8 : Create UserController class
- 5.10 Step#9 : Write UI pages(Thymeleaf)
- 6 How to test the application?
- 7 How to verify the registered users in H2 DB?
- 8 Summary
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 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.
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.
Subsequently, when you click on ‘see client side integration’ link, a new page just like below will appear.
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.
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.
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.
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.
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.
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.
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.
Step#8 : Create UserController class
Subsequently, 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’.
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.
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.
How to verify the registered users in H2 DB?
1) 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.
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.