Bird
Raised Fist0
Spring Bootframework~20 mins

UserDetailsService implementation in Spring Boot - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
UserDetailsService Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when loading a user by username?
Given this UserDetailsService implementation, what will be returned when calling loadUserByUsername("alice")?
Spring Boot
public class MyUserDetailsService implements UserDetailsService {
    private Map<String, UserDetails> users = Map.of(
        "alice", User.withUsername("alice").password("pass").roles("USER").build(),
        "bob", User.withUsername("bob").password("pass").roles("ADMIN").build()
    );

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!users.containsKey(username)) {
            throw new UsernameNotFoundException("User not found");
        }
        return users.get(username);
    }
}
AThrows UsernameNotFoundException
BReturns a UserDetails object for alice with role USER
CReturns null
DReturns a UserDetails object for bob with role ADMIN
Attempts:
2 left
💡 Hint
Check if the username exists in the users map before returning.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this UserDetailsService code
Which option contains a syntax error in the UserDetailsService implementation?
Spring Boot
public class CustomUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = User.withUsername(username).password("pass").roles("USER").build()
        return user;
    }
}
AIncorrect method name loadUserByUser
BMissing override annotation
CMissing semicolon after build() method call
DUserDetails is not imported
Attempts:
2 left
💡 Hint
Look carefully at the end of the line with build()
🔧 Debug
advanced
2:00remaining
Why does this UserDetailsService throw UsernameNotFoundException for existing user?
Given this code, why does loadUserByUsername("John") throw UsernameNotFoundException even though john exists?
Spring Boot
public class MyUserDetailsService implements UserDetailsService {
    private Map<String, UserDetails> users = new HashMap<>();

    public MyUserDetailsService() {
        users.put("john", User.withUsername("john").password("pass").roles("USER").build());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (users.get(username) == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return users.get(username);
    }
}
AThe username passed has different case than stored key
BThe users map is immutable and cannot be modified
CThe UserDetails object is null due to missing build() call
DThe users map is empty because it is not initialized properly
Attempts:
2 left
💡 Hint
Check if the username key matches exactly in case.
state_output
advanced
2:00remaining
What roles does the returned UserDetails have?
In this UserDetailsService, what roles will the UserDetails returned by loadUserByUsername("admin") have?
Spring Boot
public class AdminUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("User not found");
        }
        return User.withUsername("admin").password("adminpass").roles("ADMIN", "USER").build();
    }
}
A["ADMIN", "USER"]
B["ADMIN"]
CEmpty list
D["USER"]
Attempts:
2 left
💡 Hint
Look at the roles method call in the return statement.
🧠 Conceptual
expert
2:00remaining
What happens if UserDetailsService returns null?
In Spring Security, what is the effect if a UserDetailsService implementation returns null instead of throwing UsernameNotFoundException when a user is not found?
AAuthentication succeeds with an anonymous user
BThe application crashes with NullPointerException
CSpring Security ignores and continues authentication
DSpring Security throws an InternalAuthenticationServiceException causing authentication failure
Attempts:
2 left
💡 Hint
Think about how Spring Security handles null UserDetails.

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