DEV Community

danial
danial

Posted on

Authentication Service with Spring Boot and React client

Hello there! Have you ever wanted to build an authentication service using Spring Boot and MongoDB? If so, you’ve come to the right place! In this post, I’m going to show you how to create a simple authentication service using Spring Boot and MongoDB, which you can use as a starting point for your own projects.

Introduction

This service allows users to register, login and manage their profiles. We will use JWT tokens for authentication and authorization and will store them in a Redis database. Also the user’s data will be stored in a MongoDB database.

Prerequisites

Before we get started, make sure you have Docker installed. You’ll also need a MongoDB and a Redis database.

PS: You can use a free MongoDB Atlas account as your primary database.

To build the service, we’ll use the following tools:

  • Spring Boot: a popular Java framework for building web applications.
  • Maven: a build tool used for testing and running the backend.
  • MongoDB: a NoSQL database for storing user data.
  • Redis: an in-memory database for storing JWT tokens.
  • Docker: a platform for running applications in containers.

Building the Spring Boot Module

First, we’ll build the backend service. Create a new Spring Boot project using the Spring Initializr. Add the following dependencies to your project:

  • Spring Web
  • Spring Data MongoDB
  • Spring Security
  • jjwt: a library for working with JWTs in Java.

Next, Create a new MongoDB database and collection to store user data. In your Spring Boot application, create a new class User with the following fields:

  • id: a unique identifier for the user.
  • fullName: the user’s full name.
  • username: the user’s username.
  • password: the user’s password (stored as a hashed value).
  • phoneNumber: the user’s phone number.
  • birthday: the user’s date of birth.
  • bio: a short bio about the user. Use Spring Data MongoDB to define a repository interface for the User class, which you’ll use to interact with the database.

Implement the registration endpoint. Create a new REST controller class auth controller with a signup method that accepts a JSON payload containing the user’s registration data. Storing hashed password in the database.

Implement the login endpoint. Create a new method signin in the auth controller class that accepts a JSON payload containing the user’s login credentials. Use Spring Security’s AuthenticationManager to authenticate the user’s credentials, and if successful, generate and return a new JWT token.

Building the React Client

Now, let’s move on to the frontend. Create a new React app using:

npx create-react-app auth-client
cd auth-client
npm start
Enter fullscreen mode Exit fullscreen mode

In the src folder, create a new folder called auth . This folder will contain the logic for making API requests and page UIs.

Implement the following functions inside :

  • register: sends a POST request to the registration endpoint with the user's -registration data.
  • verification: sends a POST request to the verification endpoint with user's username and verify code.
  • login: sends a POST request to the login endpoint with the user's login credentials.
  • logout: clears the JWT token from local storage.

Use the useState hook to create state variables page inputs. Use the onChange event to update these state variables.

Use the useEffect hook to update the isLoggedIn state variable when the component mounts. If a JWT token is stored in local storage, set isLoggedIn to true.

Why we save JWT in local storage ?

Because retrieving the token from local storage instead of cookies provides an added layer of security to our application, which is crucial in ensuring the safety and confidentiality of user data.

Setup

First, to generate credentials for Spring Boot module open a terminal and navigate to the root directory of the project, then run the following command:

bash generate_passwords.sh
Enter fullscreen mode Exit fullscreen mode

This will generate unique passwords for the MongoDB and Redis databases used by the application, as well as JWT credentials.

PS: Keep in mind that if you’re using a MongoDB Atlas database, you have to update the host and port accordingly.

Replace the KAVENEGAR_YOUR_API_KEY placeholder in the src/main/resources/application-dev.yml file with your Kavenegar API key.

To launch dockerized databases, please run the following command in your terminal:

docker-compose -f docker-compose-dependency.yml up -d - build
Enter fullscreen mode Exit fullscreen mode

To start the Spring Boot module, run the following commands:

mvn clean install
mvn spring-boot:run
Enter fullscreen mode Exit fullscreen mode

Next for the ReactJs app, run the
following commands:

npm install
npm start
Enter fullscreen mode Exit fullscreen mode

To launch Spring Boot module and the React client inside of containers, open a terminal and navigate to the root directory of each project, then run the following command in your terminal:

docker-compose up -d --build
Enter fullscreen mode Exit fullscreen mode

Conclusion

To sum up, building an authentication service using Spring Boot is a great way to provide user authentication and management. With a simple React frontend, this project can be a starting point for your own authentication service. Give it a try and have fun building!

Front-end:

source code

Back-end

source code

Top comments (0)