loadUserByUsername method to find a user by usernameUserDetails object with username, password, and rolesJump into concepts and practice - no test required
loadUserByUsername method to find a user by usernameUserDetails object with username, password, and rolesusers of type UserDetails with two users: username alice with password password1, and username bob with password password2. Use User.withUsername(...).password(...).roles(...).build() to create each user with role USER.Use List.of(...) to create an immutable list of UserDetails objects.
defaultRole and set it to USER.This variable will hold the role name for users.
loadUserByUsername method with parameter username of type String. Use a for loop with variable user to iterate over users. If user.getUsername().equals(username), return user. If no user is found, throw new UsernameNotFoundException("User not found").Use a simple for loop to find the user by username and throw an exception if not found.
UserDetailsService interface and import UsernameNotFoundException. Ensure the class is public and named MyUserDetailsService.Make sure the class implements UserDetailsService and imports are complete.
What is the main purpose of implementing UserDetailsService in Spring Boot?
Which method must be overridden when implementing UserDetailsService?
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());
}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);
}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);
}