首页 > 解决方案 > 可选登录 Spring + JWT

问题描述

我尝试创建可选登录名,您可以在 Java Spring 中通过(用户名或电话号码或电子邮件)登录,我已经这样做了,但它没有用我搜索了很多但没有答案,我很确定那里是一种方法。

这是如下代码:

@Service
public class MyUserDetailsService implements UserDetailsService {

   @Autowired
   private UserRepository userRepository;

   @Override
   if(loadUserByUsername(String username)){
          public UserDetails loadUserByUsername(String username) {
             User user = userRepository.findByUsername(username);
             if (user == null) {
                throw new UsernameNotFoundException(username);
             }
             return new MyUserPrincipal(user);
           }
   } elseif(loadUserByUsername(String phone)){
          public UserDetails loadUserByUsername(String phone) {
                User user = userRepository.findByUsername(phone);
                if (user == null) {
                throw new PhoneNotFoundException(phone);
          }
          return new MyUserPrincipal(user);
   } elseif(loadUserByUsername(String email)){
            public UserDetails loadUserByUsername(String email) {
                User user = userRepository.findByUsername(email);
                if (user == null) {
                     throw new EmailNotFoundException(email);
                }
                return new MyUserPrincipal(user);
            }
   } else {
       return ex.CredentialNotFoundExptions;
   }  

我这样做是为了让用户可以选择三种方式登录,但它一直给我错误并且还没有找到答案。}

标签: javaspringspring-securityjwt

解决方案


First of all: that's not how you override in Java. @Override should sit directly above a method declaration.

Second of all: you can't put any logic outside of a method (your if-else statement).

Third of all: your if-blocks (cases) don't actually acheive anything. For Java String email and String phone are the same thing, it's just a String. So the whole if-else doesn't make sense.

I'd just go with one, overriden loadUserByUsername(), and if you want to differantiate the login types, what comes to my mind first is regex, so that the declaration would become:

@Override
public UserDetails loadUserByUsername(String login) {
    if (login.matches("(.*)@(.*).(.*)") {
        // email logic
    } else if (login.matches("[0-9]+") {
        // phone logic
    } else {
        // username logic
    }
}

It's just my first idea, for sure you could implement it in a better way. Also, the regex patterns are not ideal either, was just typing from the top of my head...


推荐阅读