UserDetailsService helps Spring Security find user info to check login details.
UserDetailsService implementation in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // find user by username // if not found, throw exception // return UserDetails object with username, password, roles } }
Implement UserDetailsService interface and override loadUserByUsername.
Throw UsernameNotFoundException if user is missing.
public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) { if (!username.equals("admin")) { throw new UsernameNotFoundException("User not found"); } return User.withUsername("admin") .password("password") .roles("USER") .build(); } }
public class MyUserDetailsService implements UserDetailsService { private final UserRepository userRepository; public MyUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) { UserEntity user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User not found")); return User.withUsername(user.getUsername()) .password(user.getPassword()) .roles(user.getRole()) .build(); } }
This service checks if the username is 'user1'. If yes, it returns user details with password and role. Otherwise, it throws an error.
package com.example.security; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Service; @Service public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if (!"user1".equals(username)) { throw new UsernameNotFoundException("User not found: " + username); } return User.withUsername("user1") .password("{noop}pass123") .roles("USER") .build(); } }
Use {noop} prefix in password if you don't want encoding for demo.
Always throw UsernameNotFoundException if user is missing to inform Spring Security.
Use User.withUsername() builder to create UserDetails easily.
UserDetailsService loads user info for Spring Security login.
Override loadUserByUsername to fetch user data.
Throw exception if user not found to handle login errors.
Practice
What is the main purpose of implementing UserDetailsService in Spring Boot?
Solution
Step 1: Understand the role of UserDetailsService
UserDetailsService is used by Spring Security to load user data during login.Step 2: Identify its main function
It fetches user details like username, password, and roles for authentication.Final Answer:
To load user-specific data during authentication -> Option BQuick Check:
UserDetailsService purpose = Load user data [OK]
- Confusing UserDetailsService with database config
- Thinking it handles HTTP requests
- Assuming it manages app properties
Which method must be overridden when implementing UserDetailsService?
Solution
Step 1: Recall UserDetailsService interface
It declares a single method named loadUserByUsername.Step 2: Confirm method signature
The method takes a username string and returns UserDetails or throws exception.Final Answer:
loadUserByUsername(String username) -> Option DQuick Check:
Method to override = loadUserByUsername [OK]
- Trying to override non-existent methods
- Confusing with repository methods
- Using wrong method signatures
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());
}Solution
Step 1: Check user existence condition
If user is not found, user.isEmpty() is true.Step 2: Analyze exception throwing
Throws UsernameNotFoundException which stops authentication process.Final Answer:
Throws UsernameNotFoundException stopping login -> Option AQuick Check:
User not found = Exception thrown [OK]
- Returning null instead of throwing exception
- Ignoring empty user Optional
- Not handling exception properly
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);
}Solution
Step 1: Check handling of missing user
Returning null on user not found is incorrect for Spring Security.Step 2: Correct approach for missing user
Should throw UsernameNotFoundException to stop authentication properly.Final Answer:
Returning null instead of throwing UsernameNotFoundException -> Option AQuick Check:
Missing user must throw exception, not return null [OK]
- Returning null causes NullPointerException later
- Ignoring exception requirement
- Assuming @Override is mandatory (optional but recommended)
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);
}Solution
Step 1: Verify user fetching with exception
Uses orElseThrow to throw UsernameNotFoundException if user missing, correct behavior.Step 2: Check role mapping to authorities
Maps user roles to GrantedAuthority list properly using stream and SimpleGrantedAuthority.Step 3: Confirm UserDetails creation
Creates Spring Security User object with username, password, and authorities as expected.Final Answer:
Correctly fetches user and maps roles to authorities -> Option CQuick Check:
User fetch + role mapping = Correct implementation [OK]
- Not throwing exception on missing user
- Forgetting to map roles to authorities
- Using deprecated or incorrect stream methods
