Spring Boot Registration and Login Tutorial with MySQL | Complete Guide

Spring Boot Registration and Login Tutorial with MySQL | Complete Guide

AI Reading

Quick summary of this article

This tutorial provides a step-by-step guide to building a user registration and login system using Spring Boot, Spring Security, MySQL, and Thymeleaf. It covers creating a new Spring Boot project, configuring a MySQL database, setting up a User entity with validation, implementing a service layer with BCrypt password encryption, and configuring Spring Security for authentication. The guide also includes creating controllers for handling registration and login requests, along with simple Thymeleaf HTML views for the user interface.

  • Uses Spring Boot 3.x with dependencies: Spring Web, Spring Data JPA, Spring Security, MySQL Driver, Thymeleaf, and Validation.
  • Stores user data in a MySQL database with password encryption using BCryptPasswordEncoder.
  • Implements Spring Security with custom login page, form-based authentication, and logout functionality.
  • Includes validation for user input (name, email, password) and checks for duplicate email addresses during registration.
  • Provides Thymeleaf templates for register, login, and home pages with a simple, functional design.

Spring Boot Register and Login Tutorial with MySQL Database

If you’re learning Spring Boot, one of the best beginner projects is building a user registration and login system with a MySQL database. In this tutorial, we’ll create a fully working authentication system from scratch.

1. Project Overview

  • User Registration – Create new accounts
  • User Login – Login using email & password
  • Password Encryption – Using BCrypt
  • MySQL Database – Store users
  • Spring Boot + Spring Security – For authentication

2. Prerequisites

  • Java 17+
  • Maven
  • MySQL Server
  • IDE – IntelliJ or Eclipse

3. Create Spring Boot Project

Use Spring Initializr with the following settings:

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.x.x
  • Dependencies: Spring Web, Spring Data JPA, Spring Security, MySQL Driver, Thymeleaf, Validation

4. Configure MySQL Database


spring.datasource.url=jdbc:mysql://localhost:3306/user_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.thymeleaf.cache=false

5. Create User Entity


package com.acesoftech.springbootrestapi.model;

import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty(message = "Name is required")
    private String name;

    @Email(message = "Please enter a valid email")
    @NotEmpty(message = "Email is required")
    @Column(unique = true)
    private String email;

    @NotEmpty(message = "Password is required")
    private String password;
}

6. Create Repository


package com.acesoftech.springbootrestapi.repository;

import com.acesoftech.springbootrestapi.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}

7. Create Service Layer


package com.acesoftech.springbootrestapi.service;

import com.acesoftech.springbootrestapi.model.User;

public interface UserService {
    void save(User user);
    User findByEmail(String email);
}

package com.acesoftech.springbootrestapi.service;

import com.acesoftech.springbootrestapi.model.User;
import com.acesoftech.springbootrestapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public void save(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
}

8. Configure Spring Security


package com.acesoftech.springbootrestapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/register", "/login", "/css/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(login -> login
                .loginPage("/login")
                .defaultSuccessUrl("/home", true)
                .permitAll()
            )
            .logout(logout -> logout.permitAll());

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }
}

9. Create Controllers


package com.acesoftech.springbootrestapi.controller;

import com.acesoftech.springbootrestapi.model.User;
import com.acesoftech.springbootrestapi.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("user") User user,
                               BindingResult result, Model model) {
        if (userService.findByEmail(user.getEmail()) != null) {
            result.rejectValue("email", null, "Email already exists");
        }
        if (result.hasErrors()) {
            return "register";
        }
        userService.save(user);
        return "redirect:/login?success";
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/home")
    public String homePage() {
        return "home";
    }
}

10. Create HTML Views (Thymeleaf)


<!-- register.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Register</title>
</head>
<body>
<h2>Register</h2>
<form th:action="@{/register}" method="post" th:object="${user}">
    Name: <input type="text" th:field="*{name}"><br>
    Email: <input type="email" th:field="*{email}"><br>
    Password: <input type="password" th:field="*{password}"><br>
    <button type="submit">Register</button>
</form>
</body>
</html>

<!-- login.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
</head>
<body>
<h2>Login</h2>
<form th:action="@{/login}" method="post">
    Email: <input type="email" name="username"><br>
    Password: <input type="password" name="password"><br>
    <button type="submit">Login</button>
</form>
</body>
</html>

<!-- home.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
<h2>Welcome to Home Page</h2>
<a th:href="@{/logout}">Logout</a>
</body>
</html>

11. Run the Project


mvn spring-boot:run

12. Conclusion

You’ve successfully built a Spring Boot Register/Login system with MySQL using Spring Security and Thymeleaf. You now have a secure authentication setup with password encryption and database integration.

Leave a Reply

Your email address will not be published. Required fields are marked *