Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 35

Secure User Registration with BCrypt

This lesson is built with resources from youtube.com, dev.to and 1 more site.

Hello! Welcome back to our course on building a production-grade blog platform.

In our last lesson, we laid the critical security groundwork. We configured a SecurityFilterChain, drawing a direct parallel to Express middleware. This allowed us to define our API's security posture, making endpoints for reading posts public while securing all other endpoints. We specifically left the /api/auth/register endpoint open, preparing for today's task.

This brings us to our learning outcome: Implement a user registration endpoint that hashes passwords using BCrypt and persists user details.

Today, we will build the first functional piece of our authentication system. You'll create a new user, hash their password securely, and save their details to our PostgreSQL database. This process is very similar to creating a user registration route in a MERN stack application, and we'll highlight the parallels throughout.

1. The Importance of Password Hashing

Before we write any code, it's essential to understand why and how we secure passwords. We never store passwords in plain text. Instead, we store a one-way hash.

To grasp the difference between hashing and encryption and to understand the algorithm we'll be using, BCrypt, please watch the following video.

#34 Spring Security | Bcrypt Password Encoder

This video from Telusko clearly explains the security risks of plain-text passwords and introduces the concept of hashing with BCrypt.

Watch from the beginning to 06:17. Pay close attention to: The explanation of hashing as a one-way function. The introduction of BCrypt as a strong, adaptive hashing algorithm. The concept of 'rounds' or 'strength' and why a higher number provides more security but also requires more computation.

The key takeaway is that BCrypt is designed to be slow. This makes it resistant to brute-force attacks. The output of BCrypt is not just the hash; it includes the algorithm version, the cost factor, and a randomly generated salt, all in one string.

Bcrypt Hash String Breakdown
This image illustrates the structure of a BCrypt hash. The salt is a random value added to the password before hashing, ensuring that even two identical passwords will result in different hashes, which prevents rainbow table attacks.

2. Creating the PasswordEncoder Bean

In Spring Security, all password operations are handled through the PasswordEncoder interface. Our application needs a single, globally available instance of a BCryptPasswordEncoder. The Spring way to achieve this is by defining it as a @Bean in our SecurityConfig. This makes it manageable by the IoC container and available for dependency injection anywhere it's needed.

Open your SecurityConfig.java file and add the following bean definition:

// In SecurityConfig.java
// Make sure to import these classes
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // ... your existing configuration from the previous lesson
        return http.build();
    }

    // Add this new bean
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // Uses default strength of 10
    }
}

By defining this bean, we're telling Spring's security infrastructure, "Whenever you need to encode or verify a password, use this instance of BCryptPasswordEncoder." This will become crucial in our next lesson when we implement the login flow.


3. The User Model: Entity and Repository

Now, let's define what a "user" is in our system. We need a JPA entity to map to our database table and a repository to interact with it.

MERN Comparison

  • JPA Entity (@Entity): This is analogous to a Mongoose Schema in your MERN projects. It defines the structure of your data.
  • JPA Repository (JpaRepository): This is the equivalent of a Mongoose Model. It provides the high-level API (.save(), .findById(), etc.) for database operations.

First, create a UserRole enum to represent user roles.

  1. Create a new package: com.example.blogplatform.model.enums.
  2. Inside, create a new Enum file named UserRole.java:
package com.example.blogplatform.model.enums;

public enum UserRole {
    USER,
    ADMIN
}

Next, let's create the User entity. We will have it implement Spring Security's UserDetails interface. This is a powerful pattern that integrates our custom user model directly with the security framework.

  1. Create a new package: com.example.blogplatform.model.entity.
  2. Inside, create a class named User.java:
package com.example.blogplatform.model.entity;

import com.example.blogplatform.model.enums.UserRole;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "users") // Use "users" as table name to avoid conflict with "user" keyword in PostgreSQL
public class User implements UserDetails {

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

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

    @Column(nullable = false)
    private String password;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private UserRole role;

    // Methods from UserDetails interface
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of(new SimpleGrantedAuthority("ROLE_" + role.name()));
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }
    
    // For simplicity, we'll return true for these. In a real app,
    // you might have logic for account locking, expiration, etc.
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Finally, create the repository.

  1. Create a new package: com.example.blogplatform.repository.
  2. Inside, create an interface named UserRepository.java:
package com.example.blogplatform.repository;

import com.example.blogplatform.model.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
}

The findByUsername method is critical. Spring Data JPA automatically implements it for us, and Spring Security will use it later to fetch a user during the login process. Using Optional is a best practice to safely handle cases where the user might not exist.


4. Building the Registration Endpoint

With our data layer ready, let's build the API layer: DTO, Service, and Controller. For a detailed example of this structure, you can refer to the article "Authentication and authorization with Spring-Boot". We will implement a similar flow.

Step 1: The Registration DTO

We need an object to carry the registration data from the client. A Java Record is perfect for this immutable data-transfer role.

  1. Create a new package: com.example.blogplatform.model.dto.
  2. Inside, create a record named SignUpDto.java:
package com.example.blogplatform.model.dto;

import com.example.blogplatform.model.enums.UserRole;

public record SignUpDto(String username, String password, UserRole role) {
}

This record concisely defines the contract for our registration request body. The article "Spring Boot 3 + Record-Based DTOs" explains more about the benefits of this modern approach.

Step 2: The Authentication Service

The service layer contains the core business logic.

  1. Create a new package: com.example.blogplatform.service.
  2. Inside, create a class named AuthService.java.
package com.example.blogplatform.service;

import com.example.blogplatform.model.dto.SignUpDto;
import com.example.blogplatform.model.entity.User;
import com.example.blogplatform.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor // Lombok annotation for constructor injection
public class AuthService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public User signUp(SignUpDto signUpDto) {
        // Check if user already exists
        userRepository.findByUsername(signUpDto.username()).ifPresent(u -> {
            throw new IllegalArgumentException("Username already taken");
        });

        // Create a new User entity
        var user = User.builder()
                .username(signUpDto.username())
                .password(passwordEncoder.encode(signUpDto.password())) // Hash the password
                .role(signUpDto.role())
                .build();

        // Save the user to the database
        return userRepository.save(user);
    }
}

Key Points:

  • @RequiredArgsConstructor: This Lombok annotation generates a constructor with all final fields, allowing Spring to perform constructor-based dependency injection. This is the modern, recommended way to inject dependencies.
  • passwordEncoder.encode(): Here is where we use the PasswordEncoder bean we created earlier. It takes the raw password from the DTO and produces a secure BCrypt hash.

Step 3: The Authentication Controller

The final piece is the controller, which exposes our logic as a REST endpoint.

  1. Create a package: com.example.blogplatform.controller.
  2. Inside, create a class named AuthController.java.
package com.example.blogplatform.controller;

import com.example.blogplatform.model.dto.SignUpDto;
import com.example.blogplatform.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @PostMapping("/register")
    public ResponseEntity<String> signUp(@RequestBody SignUpDto signUpDto) {
        authService.signUp(signUpDto);
        return new ResponseEntity<>("User registered successfully!", HttpStatus.CREATED);
    }
}

The controller is lean. Its only job is to receive the HTTP request, delegate the processing to the AuthService, and return an appropriate HTTP response.


5. Runtime Observation and Debugging

This is the moment of truth. Let's see our code in action.

  1. Restart your Spring Boot application. Because we're using JPA's schema generation (ddl-auto: update), a users table should be automatically created in your PostgreSQL database.
  2. Open Postman and create a new POST request to http://localhost:8080/api/auth/register.
  3. Go to the "Body" tab, select "raw", and choose "JSON" from the dropdown. Enter the following payload:
    {
      "username": "testuser",
      "password": "strongPassword123",
      "role": "USER"
    }
    
  4. Send the request. You should receive a 201 Created status with the message "User registered successfully!".

Now for the most important step: verification.

  1. Connect to your PostgreSQL database running in Docker. You can use a tool like DBeaver, TablePlus, or the psql command line.
  2. Execute the query: SELECT * FROM users;
  3. Observe the result. You should see a new row for testuser. Look closely at the password column. It will not be strongPassword123. Instead, it will be a long string starting with something like $2a$10$.... This is the BCrypt hash! You have successfully and securely stored the user's password.

Debugging Exercise:
Try sending the exact same POST request to /api/auth/register a second time. What happens?
You will get a 500 Internal Server Error, and in your application logs, you'll see an exception related to the username uniqueness constraint. Our service logic (ifPresent(...) throw ...) catches this. In a future lesson on advanced error handling, we'll turn this into a clean 409 Conflict response.


Conclusion

Excellent work! You have successfully implemented a secure user registration endpoint. You've tied together concepts from database persistence, REST controllers, and now, core security.

Key Takeaways:

  • Passwords must always be hashed one-way using a strong, adaptive algorithm like BCrypt.
  • In Spring, the PasswordEncoder interface (and its BCryptPasswordEncoder implementation) is the standard tool for this. It should be defined as a @Bean for application-wide use.
  • The registration flow follows the standard Controller → Service → Repository pattern, with each layer having distinct responsibilities.
  • Implementing the UserDetails interface on your User entity is a key pattern for integrating your data model with Spring Security.
  • Always verify security-sensitive operations. In this case, that meant directly inspecting the database to confirm the password was hashed.

Preview of the Next Lesson:

Now that we can register users, the next logical step is to let them log in. In our next lesson, "Build a login endpoint that validates credentials and generates JWT access and refresh tokens," we will leverage the PasswordEncoder again—this time to compare a submitted password with the stored hash. We will then introduce JSON Web Tokens (JWTs) as the mechanism for managing authenticated sessions in our stateless API.