How to make a One-Time-Password service with Spring Boot and MySQL database.

Anton Smirnov
Geek Culture
Published in
6 min readFeb 15, 2022

--

Photo by Boitumelo Phetla

In the previous article, you learned about the basics of Spring Boot. How to set up your project, add project dependencies, launch your first REST API service, and how create your simple static One-Time Password service.

In this article, I want to give an example of creating a full-fledged dynamic One-Time-Password service on Spring Boot.

What you will need.

As I described above, we will create a project to simulate the operation of the OTP service using Spring Boot, Gradle, and MySQL databases. Thus, for our project, we must have the following tools and technologies:

  • Spring Boot version 2.6.3+
  • Java11+
  • Gradle 7.2+
  • MySQL 8 +
  • Any IDE of your choice. (I prefer IntelliJ IDEA)

Creating any project using Spring Boot must start with:

https://start.spring.io /

This website was created by Spring Boot developers to enable the creation of projects based on Spring Boot in record time.

I recommend that you add several dependencies at the project creation stage:

  • Spring Boot DevTools. Spring Boot provides a module called Spring Boot DevTools. DevTools stands for Developer Tool. The module aims to try and improve the development time while working with the Spring Boot application. Spring Boot DevTools pick up the changes and restart the application.
  • Spring Web. This group comprises Web, Web-Servlet, Web-Struts, and Web-Portlet. These modules provide support to create a web application.
  • MySQL Driver. MySQL JDBC and R2DBC driver.
  • Spring Data JPA. Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.
  • Lombok. Project Lombok is a java library that automatically plugs into your editor and builds tools, spicing up your java.
    Never write another getter or equals method again, with one annotation your class has a fully-featured builder, Automate your logging variables, and much more.
  • Spring Boot Actuator. Supports built-in (or custom) endpoints that let you monitor and manage your application — such as application health, metrics, sessions, etc.

For the correct work with the Lombok library and plugin, you need to add four dependencies in the build.gradle if your are using Gradle:

compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16'
testCompileOnly 'org.projectlombok:lombok:1.18.16'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.16'

or pom.xml if your using Maven:

<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
</dependencies>

For setting Lombok plugin you need:

Using IDE built-in plugin system on Windows:

File > Settings > Plugins > Browse repositories… > Search for “Lombok” > Install Plugin

Using IDE built-in plugin system on MacOs:

Preferences > Settings > Plugins > Browse repositories… > Search for “lombok” > Install Plugin

Manually:

Download the latest release and install it manually using Preferences > Plugins > Install plugin from disk… and after you need to restart IDE.

Warning! Make sure these two requirements are satisfied:

In your project: Click Preferences -> Build, Execution, Deployment -> Compiler, Annotation Processors. Click Enable Annotation Processing

Afterward, you might need to do a complete rebuild of your project via Build -> Rebuild Project.

Entity.

Entities in JPA are nothing but POJOs representing data that can be persisted in the database. An entity represents a table stored in a database. Every instance of an entity represents a row in the table.

Let’s make creates a new class OneTimePassword and fill in the following code :

In this example, I use Lombok annotations.

You can add the @Getter and @Setter annotation to any field so that Lombok automatically generates methods for getting and setting the value.
The method for getting the default value simply returns the value of the field and has the name get Foo if the field has the name foo (or isFoo if the field is of logical type). The method of setting a new default value has the name setFoo, if the field has the name foo, returns void, and has one parameter with the same type as the field itself. This method simply sets the value in the field. Lombok is a wonderful library that allows you to shorten your code and not write more Boilerplate code.

@NoArgsConstructor will generate a constructor with no parameters.

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren’t initialized where they are declared. For those fields marked with @NonNull, an explicit null check is also generated.

Furthermore, open application.properties and add database properties :

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url
=jdbc:mysql://localhost:3306/OneTimePasswordService?createDatabaseIfNotExist=true
spring.datasource.username
=
spring.datasource.password
=
spring.datasource.platform
=mysql
spring.datasource.initialization-mode
=always

createDatabaseIfNotExist=true — this parameter is used if we need to create a database, provided that it is not detected.

Now you can run the project and make sure the table is automatically created in the database.

Repository.

The repository functions as a layer to perform all database operations directly. Now let’s make the OneTimePasswordRepository interface and fill in the following code :

Helper.

It is better to put all the methods related to generating a new one time password in a separate class, the so-called helper:

Service.

This service works on the layer that connects the database layer to the controller. Now, we create the One Time Password Service interface as follows :

In the variable private final Long expiryInterval = 5L * 60 * 1000. We store our expiration variable which by default is 5 minutes.

After we created the main classes for our OneTimePassword with Entity description service. OneTimePasswordRepository is an interface that JPA uses to interact with Entity. OneTimePasswordService stores the main business logic of our service. We can create a new class controller and call our classes with the getOneTimePassword method. Similar to this:

@RequestMapping — The @RequestMapping annotation is intended to set the addresses for your controller’s methods by which they will be available to the client. In our case “/api/v1/otp”.

@GetMapping — this annotation indicates the need to process get requests.

In our case, specify that you need to listen to get requests at “create”.

Thus, the full path to the one-time password generation service looks like this:

http://localhost:8080/api/v1/otp/create/

and we get the response:

As you can see, they received a one-time password. It’s written to the database after creation along with the date label.

With each new access to endpoint create, our service will generate a new one time password and create a date label:

Spring Actuator.

After you have developed the service and deployed it in production, it is very important to monitor its performance. This is especially true for mission-critical applications, such as banking systems, in which application failure directly affects the business.

Before Spring Actuator, it was necessary to write code to check the health of the service, but there is no need to write code with Spring Actuator. Spring Actuator provides several ready-made endpoints that can be useful for monitoring the application.

To enable the Spring Boot Actuator endpoints, add the following lines to the application.properties file:

management.server.port=8081
management.endpoints.web.exposure.include
=*
management.endpoint.shutdown.enabled
=true

In the first line, we specify the port on which we will interact with the actuator. In the second line, we indicate the need to include all endpoints. The third line is responsible for disabling the service.

http://localhost:8081/actuator/health

{"status":"UP"}

Conclusion.

In this article, we have learned to generate a one-time password code for a person who wants to use our Spring Boot service. In the next part, we will integrate our one-time password service with the Login Form to the Front End. We will write a page for authorizing a new user using login, password, and one-time password. We will also cover our API service with automation scripts and the front UI form with Cypress automation scripts.

https://test-engineer.site/

Author Anton Smirnov

--

--

Anton Smirnov
Geek Culture

I’m a software engineer who specializes in testing and automation. My top languages are Java and Swift. My blog is https://test-engineer.tech/