Java Captcha Example: How to secure Spring Boot Application by Captcha Validation? Spring Boot CAPTCHA Validation java Spring by devs5003 - January 21, 2021February 13, 20242 Last Updated on February 13th, 2024 Everyone who is reading this article would have come across captcha validation while doing registration in a website or sometimes by other means. Some websites put a captcha validation in place to get rid of spammers. An application can either be accessed by human being or by a client program. Yes Of course! There is possibility that an Http client program developed by a professional hacker can access your application. In order to fill this security hole we can implement a captcha validation because a program can’t read captcha image. Therefore, as a developer, you should have knowledge of ‘How to secure your Application by Java Captcha Example using Spring Boot?’. More or less, we will learn to implement spring boot captcha. However, we can implement a captcha concept in a simple java application like servlet based web application, MVC application, Spring MVC etc. Here we will implement it in Spring Boot as it is the most demanding technology these days. Generally, we implement a captcha in Login page or Registration page to safeguard our application from hackers. Here in this article we will implement it in a user registration page in such a way that if a user doesn’t not enter the captcha or enters wrong captcha, registration will not succeed at all. Let’s talk something more about it and then start working on ‘How to secure your Application by Java Captcha Example using Spring Boot?‘. Table of Contents Toggle What Can You Expect from This Article on spring boot java captcha example?What is Captcha?What are CAPTCHAs Used for?What are the different types of captcha?Math Problem Text Based ProblemSocial Media Sign InAudio CAPTCHATime Based CAPTCHANo CAPTCHA ReCAPTCHAConfident CAPTCHASweet CAPTCHAHow to secure Spring Boot Application by Captcha Validation?What all Tools/Technologies used in this example project?Step#1: Creating Spring Boot Application using STSStep#1A: Add Captcha related dependencies in pom.xmlStep#2 : Update database properties in application.properties fileStep#3 : Create User Entity & Repository interfaceStep#4 : Create Service Interface & Service Implementation classStep#5 : Create a Utility class to generate Captcha Step#6 : Create a UserController classStep#7 : Write UI pages(Thymeleaf) How to test the application?How to verify the registered users in H2 DB?Conclusion What Can You Expect from This Article on spring boot java captcha example? Once you complete going through this article, you will be able to answer : 1) How can a hacker access your application? 2) Why did we need Captcha? 3) What is Captcha? 4) What are the usage of Captcha? 5) What are the different types of Captcha? 6) How will you implement a java Captcha example validation using 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 Captcha integrated application? 11) Last but not the least ‘How to secure Spring Boot Application by Captcha Validation?’. In a nutshell, java captcha example. What is Captcha? A CAPTCHA is an acronym for “Completely Automated Public Turing test to tell Computers and Humans Apart“. It is a type of challenge–response test to determine whether the user is human or not. Basically Captcha is a kind of tool to differentiate between human users and automated users such as bots. Captcha provides an authorization test that is easy for a human being to perform. On the other hand it becomes relatively difficult to perform in a computer program. For example, recognizing elongated letters or numbers, or clicking on an area with a specific image. What are CAPTCHAs Used for? Primarily any website or application that wants to block the usage by computer programs such as bots uses Captcha. Some Other usage includes: 1) We can use Captcha to protect bots from spamming registration process. They can even create dummy & fake accounts. 2) We can use Captcha to protect bots from spamming contact forms on the website. 3) Also Captcha can prevent bots from spamming reviews on the websites. 4) In addition, a ticketing application can use captcha. It can limit agents from purchasing a huge number of tickets for resale. What are the different types of captcha? Math Problem This is one of the simple and popular type of Captcha, where a math problem appears on the website. For example, a user may have to solve and enter the answer for a given math problem such as “1+3”. This can be difficult for a bot to solve and enter an answer for, which makes this type of CAPTCHA more secure. Text Based Problem This type of CAPTCHA has a simple text problem for the user. These CAPTCHAs can use known words or phrases, or random combinations of digits and letters. They also may have combination of lower or upper case letters. It might offer the user to retype it as it is. Social Media Sign In Another way to offer CAPTCHA is to have users sign in using their Facebook, Google, Instagram, LinkedIn or other social media account. This also means that the user is verified to sign in without having to enter in any information. A strong point of having a website linked to social media accounts is that bots can’t sign in because they don’t have a social media account to use. Audio CAPTCHA They are as an alternative that grants accessibility to visually impaired users. Audio CAPTCHAs offers an audio recording of a sequence of letters or numbers. User needs to listen audio and then enter the same. Time Based CAPTCHA This type of CAPTCHA also has an easy way to identify whether it is a human user or a bot. It records the amount of time it takes a user to fill out their information on a form. It will probably take a bit of time to fill out a form, if it is a human user. On the other hand, Bots will fill out a form almost like a shot. No CAPTCHA ReCAPTCHA This type of CAPTCHA has been created by Google. Sometimes in short we call it Google reCAPTCHA. The task to the user is to click on a box stating, “I am not a robot”. It could also involve clicking on the box with the finger, rather than the mouse if used with phone or mobile apps. Confident CAPTCHA This type of CAPTCHA offers users to follow some kind of instruction and match images. For example, they might be instructed to, “Click on each image that has a street light sign in it”. Sweet CAPTCHA It offers the user to perform some kind of job where they are moving or matching items to one another. An example would be showing an image of a box with other images next to it. The CAPTCHA will ask the user to place the ball into the box to verify their human nature. How to secure Spring Boot Application by Captcha Validation? We will start with creating a User Registration form. First, we will take three fields. User name, User Email and a Captcha field. Further, we will declare two more supporting fields for captcha. We will consider implementing the most popular text based captcha. If the user enters correct values of Captcha image, the registration process will proceed. On successful registration a page with a list of all users will appear. Let’s start doing the whole implementation step by step. What all Tools/Technologies used in this example project? Below is the list of tools/technologies that we have used in our spring boot captcha example. ♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE ♥ Dependent Starters : Spring Web, Thymeleaf, Spring Data JPA, H2 Database, Lombok, Spring Boot DevTools ♦ JDK-8 or later versions (Extremely tested on JDK8, JDK11 and JDK14) Step#1: Creating Spring Boot Application 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 separate article on ‘Lombok‘. Step#1A: Add Captcha related dependencies in pom.xml Furthermore, in order to get Captcha features, you need to add two dependencies in your pom.xml. You can find an open source java library form here. <!-- https://mvnrepository.com/artifact/cn.apiclub.tool/simplecaptcha --> <dependency> <groupId>cn.apiclub.tool</groupId> <artifactId>simplecaptcha</artifactId> <version>1.2.2</version> <!-- we have to manage version here --> </dependency> <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </dependency> Step#2 : Update database properties in application.properties file Update application.properties to connect with H2 Database accordingly. Please note that, here we are using H2 in-memory database. However, you can use any other DB as per your requirement. For example, the file will look like as below. # application.properties --------------------------------------------- server.port=8080 spring.jpa.show-sql=true spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:captchadb Step#3 : Create User Entity & Repository interface Now create User.java & UserRepositoty.java as we use to create in a simple user registration flow. User.java package com.dev.spring.captcha.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Transient;import lombok.Data;@Data@Entitypublic class User { @Id @GeneratedValue private Integer id; private String name; private String email; @Transient private String captcha; @Transient private String hiddenCaptcha; @Transient private String realCaptcha;} UserRepository .java package com.dev.spring.captcha.repo;import org.springframework.data.jpa.repository.JpaRepository;import com.dev.spring.captcha.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.spring.captcha.service;import java.util.List;import java.util.Optional;import com.dev.spring.captcha.model.User;public interface IUserService { void createUser(User user); List<User> getAllUsers(); Optional<User> getOneUser(Integer Id);} UserServiceImpl.java package com.dev.spring.captcha.service;import java.util.List;import java.util.Optional;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.dev.spring.captcha.model.User;import com.dev.spring.captcha.repo.UserRepository;@Servicepublic class UserServiceImpl implements IUserService { @Autowired private UserRepository repo; @Override public void createUser(User user) { repo.save(user); } @Override public List<User> getAllUsers() { return repo.findAll(); } @Override public Optional<User> getOneUser(Integer id) { return repo.findById(id); }} Step#5 : Create a Utility class to generate Captcha This class will create a captcha and encode the same in a binary string from. We will name it as CaptchaUtil.java as below. ♥ Please remember that this class is the heart of all our code that offers us to implement the functionality related to Captcha. CaptchaUtil.java package com.dev.spring.captcha.util;import java.io.ByteArrayOutputStream;import java.util.Base64;import javax.imageio.ImageIO;import cn.apiclub.captcha.Captcha;import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer;import cn.apiclub.captcha.noise.CurvedLineNoiseProducer;import cn.apiclub.captcha.text.producer.DefaultTextProducer;import cn.apiclub.captcha.text.renderer.DefaultWordRenderer;public class CaptchaUtil { //Creating Captcha Object public static Captcha createCaptcha(Integer width, Integer height) { return new Captcha.Builder(width, height) .addBackground(new GradiatedBackgroundProducer()) .addText(new DefaultTextProducer(), new DefaultWordRenderer()) .addNoise(new CurvedLineNoiseProducer()) .build(); } //Converting to binary String public static String encodeCaptcha(Captcha captcha) { String image = null; try { ByteArrayOutputStream bos= new ByteArrayOutputStream(); ImageIO.write(captcha.getImage(),"jpg", bos); byte[] byteArray= Base64.getEncoder().encode(bos.toByteArray()); image = new String(byteArray); } catch (Exception e) { e.printStackTrace(); } return image; }} Step#6 : Create a UserController class Subsequently, write a controller class for User as ‘UserController.java’ which will control the user registration page. UserController.java package com.dev.spring.captcha.controller;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 com.dev.spring.captcha.model.User;import com.dev.spring.captcha.service.IUserService;import com.dev.spring.captcha.util.CaptchaUtil;import cn.apiclub.captcha.Captcha;@Controller@RequestMapping("/user")public class UserController { @Autowired private IUserService service; @GetMapping("/register") public String registerUser(Model model) { User user = new User(); getCaptcha(user); model.addAttribute("user", user); return "registerUser"; } @PostMapping("/save") public String saveUser( @ModelAttribute User user, Model model ) { if(user.getCaptcha().equals(user.getHiddenCaptcha())) { service.createUser(user); model.addAttribute("message", "User Registered successfully!"); return "redirect:allUsers"; } else { model.addAttribute("message", "Invalid Captcha"); getCaptcha(user); model.addAttribute("user", user); } return "registerUser"; } @GetMapping("/allUsers") public String getAllUsers(Model model) { List<User> userList= service.getAllUsers(); model.addAttribute("userList", userList); return "listUsers"; } private void getCaptcha(User user) { Captcha captcha = CaptchaUtil.createCaptcha(240, 70); user.setHiddenCaptcha(captcha.getAnswer()); user.setCaptcha(""); // value entered by the User user.setRealCaptcha(CaptchaUtil.encodeCaptcha(captcha)); } } Step#7 : 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. Here we have also used bootstrap for page designing. 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" /></head><body><div class="container p-3 my-3 border"> <div class="card"> <div class="card-header bg-info text-black"> <h3>USER REGISTRATION PAGE</h3> </div> <div class="card-body"> <form th:action="@{/user/save}" method="POST" th:object="${user}"> <input type="hidden" th:field="*{id}"> <div class="row"> <div class="col-2"> <label>NAME</label> </div> <div class="col-4"> <input type="text" th:field="*{name}" class="form-control"/> </div> </div><!-- NAME : <input type="text" th:field="*{name}" /> --> <br> <div class="row"> <div class="col-2"> <label>EMAIL</label> </div> <div class="col-4"> <input type="text" th:field="*{email}" class="form-control"/> </div> </div> <br> <div class="row"> <div class="col-2"> <label>CAPTCHA</label> </div> <div class="col-4"> <img th:src="*{'data:realCaptcha/jpg;base64,'+ realCaptcha}"/> </div> </div> <br> <div class="row"> <div class="col-2"> <label>ENTER CAPTCHA</label> </div> <div class="col-4"> <input type="hidden" th:field="*{hiddenCaptcha}"/> <input type="text" th:field="*{captcha}" class="form-control"/> </div> </div> <br><!-- EMAIL : <input type="text" th:field="*{email}" /> --> <div class="col-md-4 col-md-offset-4 text-center"> <input type="submit" value="Register" class="btn btn-success" /> </div></form><br/> </div> <div th:if="${message!=null}" class="card-footer bg-info text-white"> <span class="alert alert-danger" th:text="${message}"></span> </div> </div></div></body></html> listUsers.html <!DOCTYPE html><html xmlns:th="https://www.thymeleaf.org/"><head><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"> <div class="card"> <div class="card-header bg-info text-black"> <h3>USERS LIST</h3> </div> <div class="card-body"> <table class="table"> <tr> <th>ID</th> <th>NAME</th> <th>EMAIL</th> </tr> <tr th:each="ob:${userList}"> <td th:text="${ob.id}"></td> <td th:text="${ob.name}"></td> <td th:text="${ob.email}"></td> </tr> </table> </div> </div> <br/> <a th:href="@{/user/register}" class="btn btn-info">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) Enter the registration page URL http://localhost:8080/user/register into the browser. 3) Fill up the values in the fields including captcha and click on the ‘Register’ button accordingly. 4) If you fill the correct value of captcha you will be redirected to the User List page. You can see the details of the registered user. Further to register other user you can click on ‘ADD USER’ button. 5) If you don’t fill the value of captcha or fill the wrong value, you will get ‘Invalid Captcha’ message at the footer of the form. How to verify the registered users in H2 DB? 1) In order to check H2-DB console, type http://localhost:8080/h2-console/ into the new browser window 2) Enter JDBC URL value as ‘jdbc:h2:mem:captchadb’ 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 only till the session is valid. As mentioned earlier, you can also use other DB as per your requirement. Conclusion After going through all the theoretical & example part of ‘How to secure Spring Boot Application by java Captcha Example?’, finally, we are able to implement Captcha security in a Spring Boot project. Similarly, we expect from you to further extend this spring boot captcha example and implement it in your project accordingly. In order to learn the validation using Google reCAPTCHA in Spring Boot, kindly visit Google reCAPTCHA validation in Spring Boot. You can also check more details on Captcha integration from the captcha specific website. In addition, If there is any update in future, we will also update the article accordingly. Moreover, Feel free to provide your comments in comments section below. Related