【问题标题】:How to correctly implement the UserDetailsService without having an username?如何在没有用户名的情况下正确实现 UserDetailsS​​ervice?
【发布时间】:2020-04-29 01:01:42
【问题描述】:

我正在 spring-boot 中创建一个 oauth 服务,并希望使用来自 MariaDB 的用户信息进行身份验证。 在实现 UserDetailsS​​ervice 时,我必须重写函数 loadUserByUsername。问题是我的用户模型没有字段用户名,而不是我想使用他们的邮件地址加载用户。 所以我的问题是:如何在没有用户名的情况下正确实现 UserDetailsS​​ervice?

【问题讨论】:

    标签: java spring spring-boot oauth userdetailsservice


    【解决方案1】:

    那么邮件地址就是用户名。

    它只是一个文本值,用于唯一标识用户与域。它可以是:

    • 登录名(域:应用程序)
    • 电子邮件地址(域:全球)
    • SSN (域:美国居民)
    • 学生证(域:学校)
    • 员工 ID (域:公司)
    • 玩家 ID (域:游戏网站)
    • 或任何你想要的

    只要是唯一的,这样loadUserByUsername就能准确找到一条记录。

    【讨论】:

      【解决方案2】:

      选项 1 可以是您必须在用户名和字段中传递 emailId 并使用 emailId 在您的自定义 UserDetailsS​​ervice 中进行验证

      选项 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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-25
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 2013-05-12
        • 2017-10-27
        • 1970-01-01
        • 2021-07-19
        相关资源
        最近更新 更多