Bird
Raised Fist0
Spring Bootframework~10 mins

UserDetailsService implementation in Spring Boot - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the UserDetailsService implementation class.

Spring Boot
public class [1] implements UserDetailsService {
    // implementation
}
Drag options to blanks, or click blank then click option'
AUserDetails
BUserService
CMyUserDetailsService
DUserRepository
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class name that does not reflect its purpose.
Not implementing UserDetailsService interface.
2fill in blank
medium

Complete the method signature to override loadUserByUsername.

Spring Boot
@Override
public [1] loadUserByUsername(String username) throws UsernameNotFoundException {
    // method body
}
Drag options to blanks, or click blank then click option'
Avoid
BUserDetails
CUser
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Returning void or wrong type.
Missing the @Override annotation.
3fill in blank
hard

Fix the error in fetching user by username from repository.

Spring Boot
User user = userRepository.[1](username);
if (user == null) {
    throw new UsernameNotFoundException("User not found");
}
Drag options to blanks, or click blank then click option'
AfindByUsername
BfindById
CgetUser
DloadUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using findById which expects an ID, not username.
Using non-existent methods like getUser or loadUser.
4fill in blank
hard

Fill both blanks to return a UserDetails object with username and password.

Spring Boot
return new org.springframework.security.core.userdetails.User([1], [2], new ArrayList<>());
Drag options to blanks, or click blank then click option'
Auser.getUsername()
Buser.getPassword()
Cuser.getEmail()
Duser.getRoles()
Attempts:
3 left
💡 Hint
Common Mistakes
Using email instead of username.
Using roles where password is expected.
5fill in blank
hard

Fill all three blanks to complete the UserDetailsService implementation with repository injection and method.

Spring Boot
public class MyUserDetailsService implements UserDetailsService {

    private final [1] userRepository;

    public MyUserDetailsService([2] userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.[3](username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
    }
}
Drag options to blanks, or click blank then click option'
AUserRepository
CfindByUsername
DUserService
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong repository type or service class.
Using incorrect method names for fetching user.

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