如何使用Spring Boot和Hibernate加密密码以存储在数据库中

问题描述

我有一个注册页面,我在其中获取用户详细信息。我需要使用spring security来加密我的密码并将其存储在数据库中。我正在使用BCryptPasswordEncoder,但显示原始密码不能为null。输出java.lang.IllegalArgumentException:rawPassword不能为null。我不知道我在哪里做错了。卡在上面超过3天 在我的控制器类中

     @RequestMapping(value="/registerNewCustomer")
     public String showCustomerRegistration(Customer customer) {
        customer.setPassword(passwordEncoder.encode(customer.getpassword()));
        customerService.saveCustomer(customer);
        return "customer";
    }

    
    My security config class has following information

@配置 @EnableWebSecurity 公共类SecurityConfig扩展了WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    // Enable jdbc authentication
        @Autowired
        public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder());
        }
    
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/").permitAll();
    }

}

解决方法

使用密码加密可以加密密码,这是一种单向加密,当您尝试检查密码时需要加密,然后再进行匹配

public PasswordEncoder passwordEncoder(){
    PasswordEncoder encoder = new BCryptPasswordEncoder(16);
    return encoder;
}