Spring Security – Bài 2- Tùy chỉnh Login và Xác thực với User từ Database

Spring Security + JPA – Xác thực từ cơ sở dữ liệu

Mục tiêu

  • Xây dựng được hệ thống xác thực với người dùng lưu trong cơ sở dữ liệu.
  • Tùy chỉnh giao diện trang login, xử lý lỗi đăng nhập.
  • Mã hóa mật khẩu an toàn với BCrypt.
  • Phân quyền truy cập dựa trên vai trò (ROLE_USER, ROLE_ADMIN) lưu trong database.
  • Xây dựng chức năng đăng ký người dùng mới.
  • Công việc:
    • Tạo bảng users trong MySQL.
    • Sử dụng Spring Data JPA để truy xuất thông tin người dùng.
    • Tích hợp Spring Security để xác thực người dùng từ database.

Chú ý: full code dự án bạn đọc có thể xem tại: https://github.com/maicuongtho/SOT383-Web2CLC/tree/main/DemoSecurity2JPA

1. Chuẩn bị cơ sở dữ liệu

Tạo CSDL:

CREATE DATABASE demo_security;
users                     roles                    user_roles
+-------------+          +-------------+          +-------------+
| id (PK)     |          | id (PK)     |          | user_id (FK)|
| username    |          | name        |          | role_id (FK)|
| password    |          +-------------+          +-------------+
| enabled     |
+-------------+
  • users: lưu thông tin tài khoản.
  • roles: lưu danh sách vai trò (ROLE_USER, ROLE_ADMIN…).
  • user_roles: bảng trung gian thể hiện quan hệ nhiều-nhiều giữa user và role.

Mã SQL tạo các bảng :

-- Tạo bảng users
CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    enabled BOOLEAN NOT NULL DEFAULT TRUE
);

-- Tạo bảng roles
CREATE TABLE roles (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL UNIQUE
);

-- Tạo bảng trung gian user_roles
CREATE TABLE user_roles (
    user_id BIGINT NOT NULL,
    role_id BIGINT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);

2. Cấu hình application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/demo_security
spring.datasource.username=root
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true

3. Tạo Entity

3.1. Entity User

package ntu.maicuongtho.DemoSecurity2JPA.models;

import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;

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

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

    @Column(unique = true, nullable = false, length = 50)
    private String username;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private boolean enabled = true;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roles = new HashSet<>();
    //getter, setter, contrstructor
}

Giải thích:

  • enabled: có thể vô hiệu hóa tài khoản mà không cần xóa.
  • @ManyToMany(fetch = EAGER): lấy luôn danh sách roles khi load user (cần cho phân quyền).
  • @JoinTable: tạo bảng trung gian user_roles – nếu bảng đã tồn tại, JPA sẽ dùng nó.

2.2. Entity Role

package ntu.maicuongtho.DemoSecurity2JPA.models;

import jakarta.persistence.*;

@Entity
@Table(name = "roles")
public class Role {

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

    @Column(unique = true, nullable = false, length = 50)
    private String name;  // Ví dụ: ROLE_USER, ROLE_ADMIN
//getter, setter, contrstructor
}

3. Repository

package ntu.maicuongtho.DemoSecurity2JPA.repositories;

import ntu.maicuongtho.DemoSecurity2JPA.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
}
package ntu.maicuongtho.DemoSecurity2JPA.repositories;

import ntu.maicuongtho.DemoSecurity1.models.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface RoleRepository extends JpaRepository<Role, Long> {
    Optional<Role> findByName(String name);
}

4. Tạo UserDetailsService tùy chỉnh

Spring Security yêu cầu một lớp implement UserDetailsService để cung cấp thông tin user.

4.1. Custom UserDetailsService

package ntu.maicuongtho.DemoSecurity2JPA.services;

import ntu.maicuongtho.DemoSecurity2JPA.models.User;
import ntu.maicuongtho.DemoSecurity2JPA.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));

        // Chuyển đổi từ User entity sang UserDetails của Spring Security
        return org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .roles(user.getRoles().stream().map(role -> role.getName().replace("ROLE_", "")).toArray(String[]::new))
                .disabled(!user.isEnabled())
                .build();
    }
}

Giải thích:

  • loadUserByUsername được Spring Security gọi khi cần xác thực.
  • Chúng ta lấy user từ database, nếu không thấy ném UsernameNotFoundException.
  • Sử dụng builder để tạo UserDetails với username, password, roles và trạng thái enabled.
  • Lưu ý: roles() trong builder yêu cầu không có tiền tố “ROLE_”. Nếu bạn lưu role là “ROLE_USER” thì khi gọi .roles("USER") sẽ tự động thêm tiền tố.

4.2. Cấu hình PasswordEncoder và SecurityConfig

package ntu.maicuongtho.DemoSecurity2JPA.config;

import ntu.maicuongtho.DemoSecurity2JPA.services.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

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

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/register", "/css/**", "/js/**").permitAll()
                .requestMatchers("/products/new", "/products/edit/**", "/products/delete/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .permitAll()
                .defaultSuccessUrl("/products", true)
            )
            .logout(logout -> logout
                .permitAll()
                .logoutSuccessUrl("/login?logout")
            );
        return http.build();
    }
}

5. Tùy chỉnh trang Login và xử lý lỗi

5.1. Tạo Controller cho Login và Register


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class AuthController {

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

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

5.2. Giao diện Login (templates/login.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Đăng nhập</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5" style="max-width: 400px;">
    <h2 class="text-center">Đăng nhập</h2>
    <form th:action="@{/login}" method="post">
        <div class="mb-3">
            <label>Tên đăng nhập</label>
            <input type="text" name="username" class="form-control" required autofocus>
        </div>
        <div class="mb-3">
            <label>Mật khẩu</label>
            <input type="password" name="password" class="form-control" required>
        </div>
        <div th:if="${param.error}" class="alert alert-danger">
            Sai tên đăng nhập hoặc mật khẩu
        </div>
        <div th:if="${param.logout}" class="alert alert-info">
            Bạn đã đăng xuất thành công
        </div>
        <button type="submit" class="btn btn-primary w-100">Đăng nhập</button>
        <p class="text-center mt-3">
            Chưa có tài khoản? <a th:href="@{/register}">Đăng ký ngay</a>
        </p>
    </form>
</div>
</body>
</html>

5.3. Giao diện Register (templates/register.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Đăng ký</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5" style="max-width: 400px;">
    <h2 class="text-center">Đăng ký tài khoản</h2>
    <form th:action="@{/register}" method="post" th:object="${user}">
        <div class="mb-3">
            <label>Tên đăng nhập</label>
            <input type="text" th:field="*{username}" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Mật khẩu</label>
            <input type="password" th:field="*{password}" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Nhập lại mật khẩu</label>
            <input type="password" name="confirmPassword" class="form-control" required>
        </div>
        <div th:if="${error}" class="alert alert-danger" th:text="${error}"></div>
        <button type="submit" class="btn btn-success w-100">Đăng ký</button>
        <p class="text-center mt-3">
            Đã có tài khoản? <a th:href="@{/login}">Đăng nhập</a>
        </p>
    </form>
</div>
</body>
</html>

6. Xử lý đăng ký người dùng mới

6.1. DTO để nhận dữ liệu từ form

public class UserRegistrationDTO {
    private String username;
    private String password;
    private String confirmPassword;
//getter, setter, contructor
}

6.2. Service xử lý đăng ký

package ntu.maicuongtho.DemoSecurity2JPA.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import ntu.maicuongtho.DemoSecurity2JPA.models.Role;
import ntu.maicuongtho.DemoSecurity2JPA.models.User;
import ntu.maicuongtho.DemoSecurity2JPA.models.UserRegistrationDTO;
import ntu.maicuongtho.DemoSecurity2JPA.repositories.RoleRepository;
import ntu.maicuongtho.DemoSecurity2JPA.repositories.UserRepository;

import java.util.Collections;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public void registerNewUser(UserRegistrationDTO registrationDto) {
        if (userRepository.findByUsername(registrationDto.getUsername()).isPresent()) {
            throw new RuntimeException("Username đã tồn tại!");
        }
        if (!registrationDto.getPassword().equals(registrationDto.getConfirmPassword())) {
            throw new RuntimeException("Mật khẩu xác nhận không khớp!");
        }

        User user = new User();
        user.setUsername(registrationDto.getUsername());
        user.setPassword(passwordEncoder.encode(registrationDto.getPassword()));
        user.setEnabled(true);

        // Gán role mặc định là ROLE_USER
        Role userRole = roleRepository.findByName("ROLE_USER")
                .orElseGet(() -> {
                    Role newRole = new Role();
                    newRole.setName("ROLE_USER");
                    return roleRepository.save(newRole);
                });
        user.setRoles(Collections.singleton(userRole));

        userRepository.save(user);
    }
}

6.3. Controller cho đăng ký

package ntu.maicuongtho.DemoSecurity2JPA.controllers;
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 ntu.maicuongtho.DemoSecurity2JPA.models.UserRegistrationDTO;
import ntu.maicuongtho.DemoSecurity2JPA.services.UserService;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

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

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

    @PostMapping("/register")
    public String registerUser(@ModelAttribute("user") UserRegistrationDTO registrationDto, Model model) {
        try {
            userService.registerNewUser(registrationDto);
            return "redirect:/login?registered";
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            return "register";
        }
    }
}

7. Chuẩn bị dữ liệu ban đầu

Khi ứng dụng khởi chạy lần đầu, bạn nên tạo sẵn các role và một admin. Có thể dùng CommandLineRunner để khởi tạo:

package ntu.maicuongtho.DemoSecurity2JPA;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import ntu.maicuongtho.DemoSecurity2JPA.models.Role;
import ntu.maicuongtho.DemoSecurity2JPA.models.User;
import ntu.maicuongtho.DemoSecurity2JPA.repositories.RoleRepository;
import ntu.maicuongtho.DemoSecurity2JPA.repositories.UserRepository;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        // Tạo role nếu chưa có
        Role userRole = roleRepository.findByName("ROLE_USER")
                .orElseGet(() -> {
                    Role r = new Role();
                    r.setName("ROLE_USER");
                    return roleRepository.save(r);
                });
        Role adminRole = roleRepository.findByName("ROLE_ADMIN")
                .orElseGet(() -> {
                    Role r = new Role();
                    r.setName("ROLE_ADMIN");
                    return roleRepository.save(r);
                });

        // Tạo user admin nếu chưa có
        if (userRepository.findByUsername("admin").isEmpty()) {
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin"));
            admin.setEnabled(true);
            admin.setRoles(Set.of(adminRole, userRole));
            userRepository.save(admin);
        }
    }
}

8. Tích hợp với ứng dụng quản lý sản phẩm

Bây giờ, bạn có thể dùng user từ database để đăng nhập. Chỉ những người có role ADMIN mới được thêm/sửa/xóa sản phẩm. Người dùng thường (ROLE_USER) chỉ có thể xem.

Đừng quên kiểm tra trong SecurityConfig rằng các URL được bảo vệ đúng:

.requestMatchers("/products/new", "/products/edit/**", "/products/delete/**").hasRole("ADMIN")
.anyRequest().authenticated()

9. Kiểm thử

  1. Khởi động ứng dụng. Lần đầu sẽ tự tạo bảng và user admin nhờ DataInitializer.
  2. Truy cập /login, đăng nhập với admin/admin.
  3. Thử truy cập /products/new – thành công.
  4. Đăng xuất, đăng nhập với user thường (nếu có) – chỉ xem được danh sách, không thể vào trang thêm mới.
  5. Thử đăng ký user mới qua /register, sau đó đăng nhập và kiểm tra quyền.

9. Tổng kết

  • Chúng ta đã hiểu cấu trúc cơ sở dữ liệu cho xác thực: bảng users, roles, user_roles.
  • Đã xây dựng hệ thống xác thực dựa trên database với Spring Security.
  • Sử dụng UserDetailsService tùy chỉnh để load user từ JPA.
  • Mã hóa mật khẩu bằng BCrypt.
  • Xây dựng giao diện login và register, kết hợp với Bootstrap.
  • Phân quyền dựa trên vai trò lưu trong database

Vì sao cần UserDetails trong Spring Security?

Khi Spring Security thực hiện xác thực người dùng, framework cần 1 mô hình chuẩn để:

  • Lấy được username và password,
  • Biết được người dùng có quyền hạn (roles/authorities) gì,
  • Kiểm tra trạng thái của tài khoản (có bị khóa, hết hạn, vô hiệu hóa… không).

–> Vì vậy, Spring Security định nghĩa interface UserDetails như là khuôn mẫu chuẩn.

public interface UserDetails {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}

** Vai trò trong hệ thống

  • Khi người dùng đăng nhập (POST /login hoặc gọi API bảo vệ),
  • Spring Security sẽ gọi loadUserByUsername(username) trong UserDetailsService.
  • UserDetailsService sẽ trả về một đối tượng UserDetails chứa toàn bộ thông tin cần thiết về người dùng.

Spring sẽ dùng các thông tin đó để:

  • Kiểm tra mật khẩu.
  • Kiểm tra tài khoản có bị khóa / vô hiệu hóa / hết hạn không.
  • Gán các quyền cho người dùng (authorities).

* Vì sao không trả thẳng Entity User?

  • User của bạn (Entity JPA) có thể chứa rất nhiều thông tin riêng, ví dụ như email, số điện thoại, ngày sinh, ảnh đại diện,…
  • Trong khi đó, xác thực chỉ cần một số thông tin nhỏ (username, password, roles, trạng thái tài khoản).
  • Để tách biệt trách nhiệm và giữ cho quy trình xác thực bảo mật và rõ ràng, Spring yêu cầu một đối tượng chuyên biệt là UserDetails.

–> Vậy nên, bạn tạo thêm lớp UserDetailsImpl để chuyển đổi từ Entity User thành mô hình chuẩn UserDetails.


Tóm tắt

Entity UserUserDetails
Chứa toàn bộ thông tin người dùng trong databaseChứa thông tin tối thiểu cần thiết để xác thực
Quản lý bởi JPAQuản lý bởi Spring Security
Dùng cho lưu trữ, xử lý dữ liệu nghiệp vụDùng cho quy trình xác thực (Authentication)

** Quy trình Xác thực trong Spring Security với UserDetails

[User gửi thông tin đăng nhập (username, password)]
|
v
[Spring Security nhận yêu cầu login]
|
v
[Gọi UserDetailsService.loadUserByUsername(username)]
|
v
[Tải UserDetails từ database]
- getUsername()
- getPassword()
- getAuthorities()
- isAccountNonLocked()
- isEnabled()
|
v
[Spring Security kiểm tra thông tin]
- So khớp password
- Kiểm tra trạng thái tài khoản
|
v
[Xác thực thành công ] ---> [Gán quyền vào SecurityContextHolder]
|
v
[Tiếp tục truy cập các API được bảo vệ]

Các thành phần chính tham gia:

Thành phầnVai trò
AuthenticationManagerQuản lý xác thực
UsernamePasswordAuthenticationTokenGói username + password
UserDetailsServiceLoad thông tin người dùng từ database
UserDetailsĐối tượng chứa thông tin xác thực chuẩn hóa
SecurityContextHolderLưu trữ thông tin người dùng sau xác thực thành công

Cách kết nối các thành phần

  • UsernamePasswordAuthenticationFilter sẽ lấy username, password từ HTTP request.
  • Gửi đến AuthenticationManager.
  • AuthenticationManager gọi UserDetailsService.loadUserByUsername().
  • UserDetailsService tìm trong CSDL → trả về UserDetails.
  • So sánh password, kiểm tra account status.
  • Nếu đúng, lưu thông tin xác thực vào SecurityContextHolder.

Dễ nhớ

UserDetails là “hộ chiếu” giúp người dùng vượt qua cổng kiểm tra an ninh (Spring Security).

Comments are closed.