java - 可选登录 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;
}
我这样做是为了让用户可以选择三种方式登录,但它一直给我错误并且还没有找到答案。}
解决方案
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...
推荐阅读
- r - 将参数作为承诺传递给使用双括号的其他函数
- java - 更改特定字段的 JSON 数据的值和类型
- python - 熊猫 to_html() col_space arg 输入
- javascript - 我正在等待来自服务器的响应,但希望在等待响应的 1 分钟后在 UI 中显示一些超时消息
- git - gitlab-ci - 有 2 个分支的仓库,2 个 gitlab-ci
- r - How to include a second axis in ggplot with another dataframe?
- javascript - 如何在不重新加载整个页面的情况下使用 django 在网站上显示数据
- postgresql - postgres 的 sql 类型(映射)无效
- python - Python 3.x,矩阵不能按预期工作
- python - 如何将具有不同数量数据点的 2 个数据集缩放到一个图表中?