我是第一次配置Spring Security,但由于出现此错误,Spring似乎看不到客户端的原始密码。
o.s.s.c.bcrypt.BCryptPasswordEncoder : Empty encoded password
这似乎是一个明显的问题,但请允许我,经过多次尝试我还是无法弄清楚。 我的SecurityConfig类是...
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService userDetailsService;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
}
这是我的UserServiceDetails服务。
公共类CustomUserDetailsService实现UserDetailsService {
@Autowired
private UserRepository repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Owner> optionalUser = repo.findByUsername(username);
optionalUser
.orElseThrow(() -> new UsernameNotFoundException("Username not
found"));
return optionalUser
.map(CustomUserDetails::new).get();
}
}
我还配置了以下bean
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
} 这是我的userService。
public class CustomUserDetails extends Owner implements UserDetails {
public CustomUserDetails(final Owner owner) {
super();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_"+getRoles()))
.collect(Collectors.toList());
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
我肯定一定会丢失一些东西,但是我似乎无法弄清楚。通过HttpRequest,我知道该密码已在我登录时发布到系统中。
答案 0 :(得分:1)
我发现OptionalUser没有正确映射到UserDetail对象,从而返回了一个新的空UserDetail对象。以下代码是错误的。
return optionalUser
.map(CustomUserDetails::new).get();
}
所以我的新UserDetailsService类是...
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
Optional<Owner> optionalUser = repo.findByUsername(username);
Owner user = optionalUser.get();
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
public Collection<? extends GrantedAuthority> getAuthorities(Owner user) {
return user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_"+user.getRoles()))
.collect(Collectors.toList());
}
}