如何通过电话和电子邮件为登录用户自定义我的UserDetailsS​​erivce实现类

时间:2017-09-07 05:02:58

标签: spring spring-boot spring-security spring-data-jpa

如何在我的代码下面的spring bot中通过电话和电子邮件为登录用户自定义我的UserDetailsSerivce实现类。 是否需要任何模式匹配? 用户可以同时登录电话和电子邮件。

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    //user can login both email and phone

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            return JwtUserFactory.create(user);
        }
    }
}

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUsername(String username);
    User findByEmail(String email);
    User findByPhone(long phone);
} 

1 个答案:

答案 0 :(得分:2)

也许是这样的?:

Optional<User> findByEmail(String email);
Optional<User> findByPhone(String phone);

@Override
public UserDetails loadUserByUsername(String input) throws UsernameNotFoundException {

    return userRepo.findByEmail(input)
            .map(user -> new User(
                    user.getName(),
                    user.getPassword(),
                    user.getRoles()))
            .orElse(userRepo.findByPhone(input)
                    .map(user -> new User(
                            user.getName(),
                            user.getPassword(),
                            user.getRoles())
                    ).orElseThrow(() -> new UsernameNotFoundException("User not found!"))
            );
}

另一种方法 - 使用regex检查输入,如果我们找到了电子邮件,则使用findByEmail或其他 - findByPhone