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?
问问题
739 次
2 回答
2
那么邮件地址就是用户名。
它只是一个文本值,用于唯一标识域中的用户。它可以是:
- 登录名(域:应用程序)
- 电子邮件地址(域:全球)
- SSN (域:美国居民)
- 学生证(域:学校)
- 员工ID (域:公司)
- 玩家 ID (域:游戏网站)
- 或任何你想要的
只要它是唯一的,那么就loadUserByUsername
可以找到恰好一条记录。
于 2020-01-11T19:16:03.553 回答
0
选项 1 可以是您必须在用户名和字段中传递 emailId 并使用 emailId 在您的自定义 UserDetailsService 中进行验证
选项 2 您需要有一些映射,您可以使用它从用户名字段中派生 emailId。
@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;
}
}
于 2020-01-11T19:10:08.337 回答