Login and Registration REST API using Spring Boot, JPA, and MySQL

Overview

Welcome to our step-by-step guide on creating secure and efficient login and registration REST APIs using Spring Boot, Spring Data JPA, and MySQL. Whether you’re a beginner or an experienced developer, this blog will walk you through the process in a simple, user-friendly manner. By the end, you’ll have a solid understanding of how to build and test these APIs, ensuring they are both functional and secure.

Login and Registration REST API using Spring Boot

Why Are Login and Registration APIs Important?

In today’s digital world, user authentication is the backbone of most web applications. Whether it’s an e-commerce platform, a social media app, or a banking system, users need a secure way to register and log in. Building robust APIs for these functionalities ensures that your application is not only user-friendly but also safe from potential security threats.

Table of Contents:

  • Set Up a Spring Boot Project and Add Dependencies.
  • Configure Mysql Database in application.properties file
  • Create User Entity class
  • Create REST APIs for Login and Registration
  • Test the APIs Using Postman

Step 1: Set Up a Spring Boot Project and Add Dependencies

1. Use Spring Initializer or an IDE like IntelliJ or Eclipse to create a new Spring Boot project. Add the following dependencies:

  • Spring Web: For building web applications and REST APIs.
  • Spring Data JPA: For interacting with the database.
  • MySQL Driver: To connect to your MySQL database.

2. Select Spring Boot version (latest stable version).

3. Generate the project and extract the downloaded zip file.

4. Open the project in IntelliJ IDEA or Eclipse.

You can also add following dependency manually in your spring boot project pom.xml


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

Step 2: Configure Mysql Database in application.properties file

Open application.properties or application.yml and add the MySQL database details. This connects your Spring Boot application to the MySQL database.


# Server Configuration
server.port = 8082

# Database Configuration
spring.datasource.url = jdbc:mysql://localhost:3306/your_database_name
spring.datasource.name = your_database_name
spring.datasource.username = your_username
spring.datasource.password = your_password
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

# JPA Configuration
spring.jpa.hibernate.ddl-auto = update

For More Details:

If you want to learn more about configuring the application.properties file, check out this detailed article:

Create REST APIs Using Spring Boot: Step-by-Step Guide

Step 3: Create User Entity Class

Create a User class to represent the user data. This class will be mapped to a database table using JPA.


package com.LoginRegister.example.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class Users {

    @Id
    private String email;
    
    private String name;
    
    private String password;

    public Users() {
    }

    public Users(String email, String name, String password) {
        super();
        this.email = email;
        this.name = name;
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Step 4: Create REST APIs for Login and Registration

1. Create User Repository

This repository interface extent the JpaRepository and perform all the database operations


package com.LoginRegister.example.repository;

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

import com.LoginRegister.example.entity.Users;

@Repository
public interface UsersRepo extends JpaRepository<Users, String> {
    
}

2. Create User Service

This service class contain all the business login also call the repository method for performing database operations


package com.LoginRegister.example.service;

import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.LoginRegister.example.entity.Users;
import com.LoginRegister.example.repository.UsersRepo;
import com.LoginRegister.example.requests.LoginRequest;

@Service
public class UserService {

    @Autowired 
    private UsersRepo usersRepo;

    public Users addUser(Users user) {
        return usersRepo.save(user);
    }

    public Boolean loginUser(LoginRequest loginRequest) {
        Optional<Users> user = usersRepo.findById(loginRequest.getUserId());

        if (user.isEmpty()) {
            return false;
        }

        Users user1 = user.get();
        return user1.getPassword().equals(loginRequest.getPassword());
    }
}

3. Create User Controller

This controller class contains all the end points for api calling


package com.LoginRegister.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.LoginRegister.example.entity.Users;
import com.LoginRegister.example.requests.LoginRequest;
import com.LoginRegister.example.service.UserService;

@RestController
public class UsersController {

    @Autowired
    private UserService userService;

    @PostMapping("/addUser")
    @CrossOrigin(origins = "http://localhost:3000")
    public ResponseEntity<Users> addUser(@RequestBody Users user) {
        Users savedUser = userService.addUser(user);
        return ResponseEntity.ok(savedUser);
    }

    @PostMapping("/loginUser")
    @CrossOrigin(origins = "http://localhost:3000")
    public ResponseEntity<Boolean> loginUser(@RequestBody LoginRequest loginRequest) {
        Boolean isAuthenticated = userService.loginUser(loginRequest);
        return ResponseEntity.ok(isAuthenticated);
    }
}

4. Create Login Request Class

These request class is used for data transfer while api calling


package com.LoginRegister.example.requests;

public class LoginRequest {
    
    public LoginRequest() {
        // Default constructor
    }
    
    public LoginRequest(String userId, String password) {
        super();
        this.userId = userId;
        this.password = password;
    }
    
    public String getUserId() {
        return userId;
    }
    
    public void setUserId(String userId) {
        this.userId = userId;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    private String userId;
    private String password;

}

Project Structure

Here’s an image showing the project structure for better understanding.

Spring Boot project structure

Step 5: Test the APIs Using Postman

Test User Registration

  • Open Postman and set the request type to POST
  • Enter the URL:
  •   
           http://localhost:8082/addUser
  • Add the following JSON body:
  •   
          {
            "name": "John Doe",
            "email": "john@example.com",
            "password": "password123"
          }
        
  • Send the request and check the response.
create rest apis using spring boot, spring data jpa and mysql

Test User Login

  • Set the request type to POST
  • Enter the URL:
  •   
           http://localhost:8082/loginUser
  • Add the following JSON body:
  •   
          {
            "email": "john@example.com",
            "password": "password123"
          }
        
  • Send the request and check the response.
create rest apis using spring boot, spring data jpa and mysql

Enhance Security

  • Always use HTTPS to encrypt data transmitted between the client and server.
  • Implement role-based access control (RBAC) to restrict access to certain endpoints.
  • Implement JSON Web Tokens (JWT) for stateless authentication.

Conclusion

Congratulations! You’ve successfully built robust login and registration REST APIs using Spring Boot, JPA, and MySQL. By following this guide, you’ve learned how to:

  • Set up a Spring Boot project.
  • Create and configure a MySQL database.
  • Implement secure user registration and login.
  • Test your APIs using Postman.

This foundation will help you build secure and scalable web applications. Happy coding!

Youtube Video –

Github Repository –

https://github.com/amangupta7024/LoginRegisterFlow-SpringBoot-React

Explore our more articles

2 thoughts on “Login and Registration REST API using Spring Boot, Data JPA and Mysql”

Leave a Comment