0
0
Spring Bootframework~30 mins

UserDetailsService implementation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
UserDetailsService Implementation in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that needs to authenticate users. To do this, you will implement the UserDetailsService interface, which loads user data for authentication.
🎯 Goal: Create a class that implements UserDetailsService to load user details from a predefined list of users.
📋 What You'll Learn
Create a list of users with username and password
Define a variable for the default user role
Implement the loadUserByUsername method to find a user by username
Return a UserDetails object with username, password, and roles
💡 Why This Matters
🌍 Real World
UserDetailsService is used in Spring Boot applications to load user information for authentication and authorization.
💼 Career
Understanding UserDetailsService is essential for backend developers working with Spring Security to implement custom authentication logic.
Progress0 / 4 steps
1
Create a list of users
Create a private final list called users 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.
Spring Boot
Need a hint?

Use List.of(...) to create an immutable list of UserDetails objects.

2
Add a role variable
Add a private final string variable called defaultRole and set it to USER.
Spring Boot
Need a hint?

This variable will hold the role name for users.

3
Implement loadUserByUsername method
Override the 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").
Spring Boot
Need a hint?

Use a simple for loop to find the user by username and throw an exception if not found.

4
Complete the UserDetailsService class
Add the class declaration to implement UserDetailsService interface and import UsernameNotFoundException. Ensure the class is public and named MyUserDetailsService.
Spring Boot
Need a hint?

Make sure the class implements UserDetailsService and imports are complete.