Bird
Raised Fist0
Spring Bootframework~10 mins

UserDetailsService implementation in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - UserDetailsService implementation
Start Authentication
Call loadUserByUsername(username)
Search user in database
Create UserDetails
Return UserDetails
Spring Security uses UserDetails for auth
End
The flow starts with Spring Security calling loadUserByUsername. The method searches the database for the user. If found, it creates and returns a UserDetails object. If not, it throws an exception.
Execution Sample
Spring Boot
public class MyUserDetailsService implements UserDetailsService {
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) throw new UsernameNotFoundException(username);
    return new MyUserDetails(user);
  }
}
This code looks up a user by username, throws if not found, and returns a UserDetails object for Spring Security.
Execution Table
StepActionInput usernameDatabase ResultException ThrownReturn Value
1Call loadUserByUsernamealiceSearch for 'alice'NoN/A
2User found in DBaliceUser object with username 'alice'NoN/A
3Create UserDetailsaliceUser objectNoUserDetails object for 'alice'
4Return UserDetailsaliceUser objectNoUserDetails object for 'alice'
5Call loadUserByUsernamebobSearch for 'bob'NoN/A
6User not foundbobnullYes: UsernameNotFoundExceptionN/A
💡 Execution stops after returning UserDetails or throwing UsernameNotFoundException.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
usernameN/Aalicealicealice
usernullUser('alice')User('alice')User('alice')
userDetailsnullnullUserDetails('alice')UserDetails('alice')
Key Moments - 2 Insights
Why do we throw UsernameNotFoundException when the user is not found?
Spring Security expects this exception to know authentication failed. See execution_table row 6 where 'bob' is not found and exception is thrown.
What does the UserDetails object represent?
It holds user info like username, password, and roles for Spring Security to check. See execution_table rows 3 and 4 where UserDetails is created and returned.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is returned at step 4 when username is 'alice'?
AUserDetails object for 'alice'
Bnull
CUsernameNotFoundException
DUser object for 'alice'
💡 Hint
Check the 'Return Value' column at step 4 in execution_table.
At which step does the exception get thrown for a missing user?
AStep 2
BStep 4
CStep 6
DStep 3
💡 Hint
Look for 'Exception Thrown' column in execution_table.
If the database returned null for username 'alice', what would happen?
AUserDetails object is returned
BUsernameNotFoundException is thrown
CNullPointerException occurs
DAuthentication succeeds anyway
💡 Hint
See execution_table row 6 for behavior when user is not found.
Concept Snapshot
UserDetailsService is a Spring Security interface.
Implement loadUserByUsername to find user by username.
Return UserDetails if found, else throw UsernameNotFoundException.
Spring Security uses UserDetails to authenticate users.
This method is called during login to verify credentials.
Full Transcript
This visual trace shows how Spring Security calls the loadUserByUsername method in a UserDetailsService implementation. The method receives a username, searches the database for a matching user, and either returns a UserDetails object or throws a UsernameNotFoundException if the user is not found. The execution table tracks each step, showing the input username, database search result, exceptions thrown, and return values. Variables like username, user, and userDetails are tracked to show their values at each step. Key moments clarify why exceptions are thrown and what UserDetails represents. The quiz tests understanding of return values and exception points. This helps beginners see exactly how user lookup works in Spring Security authentication.

Practice

(1/5)
1.

What is the main purpose of implementing UserDetailsService in Spring Boot?

easy
A. To configure database connections
B. To load user-specific data during authentication
C. To handle HTTP requests
D. To manage application properties

Solution

  1. Step 1: Understand the role of UserDetailsService

    UserDetailsService is used by Spring Security to load user data during login.
  2. Step 2: Identify its main function

    It fetches user details like username, password, and roles for authentication.
  3. Final Answer:

    To load user-specific data during authentication -> Option B
  4. Quick Check:

    UserDetailsService purpose = Load user data [OK]
Hint: UserDetailsService always loads user info for login [OK]
Common Mistakes:
  • Confusing UserDetailsService with database config
  • Thinking it handles HTTP requests
  • Assuming it manages app properties
2.

Which method must be overridden when implementing UserDetailsService?

easy
A. findUserByEmail(String email)
B. getUserRoles(String username)
C. authenticateUser(User user)
D. loadUserByUsername(String username)

Solution

  1. Step 1: Recall UserDetailsService interface

    It declares a single method named loadUserByUsername.
  2. Step 2: Confirm method signature

    The method takes a username string and returns UserDetails or throws exception.
  3. Final Answer:

    loadUserByUsername(String username) -> Option D
  4. Quick Check:

    Method to override = loadUserByUsername [OK]
Hint: Only loadUserByUsername is required in UserDetailsService [OK]
Common Mistakes:
  • Trying to override non-existent methods
  • Confusing with repository methods
  • Using wrong method signatures
3.

Given this UserDetailsService implementation snippet, what happens if the user is not found?

public UserDetails loadUserByUsername(String username) {
    Optional<User> user = userRepository.findByUsername(username);
    if (user.isEmpty()) {
        throw new UsernameNotFoundException("User not found");
    }
    return new CustomUserDetails(user.get());
}
medium
A. Throws UsernameNotFoundException stopping login
B. Returns null and allows login
C. Returns empty UserDetails object
D. Logs error but continues login

Solution

  1. Step 1: Check user existence condition

    If user is not found, user.isEmpty() is true.
  2. Step 2: Analyze exception throwing

    Throws UsernameNotFoundException which stops authentication process.
  3. Final Answer:

    Throws UsernameNotFoundException stopping login -> Option A
  4. Quick Check:

    User not found = Exception thrown [OK]
Hint: User not found must throw exception to block login [OK]
Common Mistakes:
  • Returning null instead of throwing exception
  • Ignoring empty user Optional
  • Not handling exception properly
4.

Identify the error in this UserDetailsService implementation:

public UserDetails loadUserByUsername(String username) {
    User user = userRepository.findByUsername(username);
    if (user == null) {
        return null;
    }
    return new CustomUserDetails(user);
}
medium
A. Returning null instead of throwing UsernameNotFoundException
B. Using Optional incorrectly
C. Missing @Override annotation
D. Not calling super.loadUserByUsername

Solution

  1. Step 1: Check handling of missing user

    Returning null on user not found is incorrect for Spring Security.
  2. Step 2: Correct approach for missing user

    Should throw UsernameNotFoundException to stop authentication properly.
  3. Final Answer:

    Returning null instead of throwing UsernameNotFoundException -> Option A
  4. Quick Check:

    Missing user must throw exception, not return null [OK]
Hint: Never return null; always throw UsernameNotFoundException [OK]
Common Mistakes:
  • Returning null causes NullPointerException later
  • Ignoring exception requirement
  • Assuming @Override is mandatory (optional but recommended)
5.

You want to implement UserDetailsService to load users from a database and assign roles dynamically. Which approach correctly combines fetching user data and setting roles?

public UserDetails loadUserByUsername(String username) {
    User user = userRepository.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found"));
    List<GrantedAuthority> authorities = user.getRoles().stream()
        .map(role -> new SimpleGrantedAuthority(role.getName()))
        .toList();
    return new org.springframework.security.core.userdetails.User(
        user.getUsername(), user.getPassword(), authorities);
}
hard
A. Returns user without roles assigned
B. Fails to throw exception if user missing
C. Correctly fetches user and maps roles to authorities
D. Uses deprecated method toList() causing error

Solution

  1. Step 1: Verify user fetching with exception

    Uses orElseThrow to throw UsernameNotFoundException if user missing, correct behavior.
  2. Step 2: Check role mapping to authorities

    Maps user roles to GrantedAuthority list properly using stream and SimpleGrantedAuthority.
  3. Step 3: Confirm UserDetails creation

    Creates Spring Security User object with username, password, and authorities as expected.
  4. Final Answer:

    Correctly fetches user and maps roles to authorities -> Option C
  5. Quick Check:

    User fetch + role mapping = Correct implementation [OK]
Hint: Use orElseThrow and map roles to authorities for UserDetails [OK]
Common Mistakes:
  • Not throwing exception on missing user
  • Forgetting to map roles to authorities
  • Using deprecated or incorrect stream methods