I am creating an oauth service in spring-boot and want to use user information from a MariaDB for authentication. When implementing UserDetailsService I have to override the function loadUserByUsername. The problem is that my user model does not have a field username, instead of this I want to load the users using their mail address. So my question: How do I correctly implement the UserDetailsService without having an username?
Asked
Active
Viewed 1,669 times
2 Answers
2
Then the mail address is the user name.
It is just a text value that uniquely identify the user with the domain. It can be a:
- login name (domain: application)
- email address (domain: global)
- SSN (domain: US resident)
- student id (domain: school)
- employees id (domain: company)
- gamer id (domain: game site)
- or whatever you want it to be
as long as it is unique, so that loadUserByUsername
can find exactly one record.

Andreas
- 154,647
- 11
- 152
- 247
0
Option 1 can be you have to pass the emailId in username and field and use the emailId to validate in your Custom UserDetailsService
Option 2 you need to have some mapping using which you can derive the emailId from the username field.
@Component
public class AppUserDetailsService implements UserDetailsService{
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userRepository.findByEmailId(s.toLowerCase());
if(user == null) {
throw new UsernameNotFoundException(String.format("The username %s doesn't exist", s));
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("STANDARD_USER"));
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getEmailId(), user.getPassword(), authorities);
return userDetails;
}
}

dassum
- 4,727
- 2
- 25
- 38