Class MyUserDetailsService

java.lang.Object
vaultWeb.services.auth.MyUserDetailsService
All Implemented Interfaces:
org.springframework.security.core.userdetails.UserDetailsService

@Service public class MyUserDetailsService extends Object implements org.springframework.security.core.userdetails.UserDetailsService
Service class that integrates the application's User entity with Spring Security.

Implements UserDetailsService, which is used by Spring Security during the authentication process. This service loads user-specific data given a username.

Responsibilities:

  • Retrieve a User entity from the database via UserRepository.
  • Convert the domain User into a Spring Security UserDetails object.
  • Throw UsernameNotFoundException if the user does not exist, signaling authentication failure.

Detailed workflow:

  1. Spring Security calls loadUserByUsername(String) with the username supplied during login.
  2. The method queries the UserRepository to fetch the User entity.
  3. If no user is found, a UsernameNotFoundException is thrown.
  4. If the user is found, a UserDetails object is built using:
    • username: used in the security context as the principal
    • password: hashed password stored in the database (e.g., BCrypt)
    • authorities: roles or permissions (can be added here if needed)
  5. Spring Security then compares the provided plaintext password with the stored hash using the configured PasswordEncoder.
  6. If the passwords match, authentication succeeds; otherwise, it fails.

This design decouples the application's User entity from Spring Security's internal representation, providing flexibility and security abstraction.

  • Constructor Details

    • MyUserDetailsService

      public MyUserDetailsService()
  • Method Details

    • loadUserByUsername

      public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws org.springframework.security.core.userdetails.UsernameNotFoundException
      Loads the user details for Spring Security based on the given username.
      Specified by:
      loadUserByUsername in interface org.springframework.security.core.userdetails.UserDetailsService
      Parameters:
      username - The username of the user attempting to authenticate.
      Returns:
      A UserDetails object containing the username, hashed password, and authorities.
      Throws:
      org.springframework.security.core.userdetails.UsernameNotFoundException - if the username does not exist in the database.