我正在使用springsecurity bcrypt密码编码器对我的密码进行编码这就是我保存密码的方式
public User saveUser(User newUser) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode = bCryptPasswordEncoder.encode(newUser.getPassword());
newUser.setPassword(encode);
User user = userRepo.save(newUser);
return user;
}
这就是我定义bean的方式
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
但是,当我尝试将密码与编码的密码匹配时,我无法登录。我使用了passwordencoder.matches,但没有帮助
public Response login(String username, String password) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
Response response = new Response();
Optional<User> byuser_nameAndPassword = userRepo.getByuser_nameAndPassword(username);
User user = byuser_nameAndPassword.get();
String encodedPassword = passwordEncoder.encode(password);
boolean matches = passwordEncoder.matches(encodedPassword, user.getPassword());
if (matches){
response.setStatus(201);
response.setMessage("Login Succeeded");
} else {
response.setStatus(403);
response.setMessage("You are not Authorized");
}
return response;
}
}
感谢您的帮助。
1条答案
按热度按时间z3yyvxxp1#
您正在以不正确的格式将参数传递给
boolean matches = passwordEncoder.matches(encodedPassword, user.getPassword());
文件说:布尔匹配(java.lang.charsequence(密码,java.lang.string encodedpassword)
第一个参数必须是原始密码,而不是编码密码。
应该是: