Bird
Raised Fist0
Spring Bootframework~5 mins

UserDetailsService implementation in Spring Boot

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
Introduction

UserDetailsService helps Spring Security find user info to check login details.

When you want to load user info from a database for login.
When you need to check user roles and permissions during login.
When you want to customize how user data is fetched for security.
When you want to connect Spring Security with your own user storage.
When you want to handle login errors if user not found.
Syntax
Spring Boot
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.

Examples
Simple example returning a fixed user if username is 'admin'.
Spring Boot
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();
    }
}
Example fetching user from database using a repository.
Spring Boot
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();
    }
}
Sample Program

This service checks if the username is 'user1'. If yes, it returns user details with password and role. Otherwise, it throws an error.

Spring Boot
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();
    }
}
OutputSuccess
Important Notes

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.

Summary

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

(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