我是第一次配置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服务。

公共类CustomUserDetailsS​​ervice实现UserDetailsS​​ervice {

@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中,我知道该密码已在我登录时发布到系统中。

最佳答案

我发现OptionalUser没有正确映射到UserDetail对象,从而返回了一个新的空UserDetail对象。以下代码是错误的。

return optionalUser
    .map(CustomUserDetails::new).get();
 }


所以我新的UserDetailsS​​ervice类是...

@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());
}
}

10-04 11:24