This service checks if the username is 'user1'. If yes, it returns user details with password and role. Otherwise, it throws an error.
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();
}
}