我正在使用BCryptPasswordEncoder来加密用户注册和登录。
注册部分工作正常,它将新用户放入数据库,密码如下:
'$2a$10$aUk/26idLhSaNmhNRTRejd03FnxxLxv6X0Uo0P4PcA4mbyy.
当我登录时,输入的用户名匹配,我从存储库中成功找到用户。
然后告诉我用户名或密码错误。当我从程序中删除此加密它工作正常。基本上我在比较加密密码时做错了。
这是我的UserDetailsService实现逻辑:
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
System.out.println(username);
User user = userRepository.findByUsername(username);
System.out.println(user.getPassword());
if (user.getUsername().isEmpty()) {
throw new UsernameNotFoundException(
"No user found with username: "+ username);
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new org.springframework.security.core.userdetails.User
(user.getUsername(),
user.getPassword().toLowerCase(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked,
getAuthorities(Arrays.asList("ROLE_USER")));
}
private static List<GrantedAuthority> getAuthorities (List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
我还在Web安全文件中设置了bean:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
我做错了什么?感谢。