Spring AuthenticationManagerBuilder密码哈希

时间:2015-06-12 14:43:34

标签: spring spring-security spring-boot

我试图在Spring中设置用户身份验证,但在添加密码哈希后,它不会进行身份验证。我正在使用Spring Boot和Spring Security。

以下是我的代码的缩短版本:

客户实体:

@Entity
public class Customer {

  private String username;
  private String password;

  public Customer() {
  }

  @Column
  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  @Column(length=100)
  public String getPassword() {
    return password;
  }

  public String setPassword(String password) {
    this.password = new BCryptPasswordEncoder().encode(password);
  }
}

安全配置:

@SpringBootApplication
@EnableAutoConfiguration
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private CustomerRepository customerRepository;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().fullyAuthenticated().and().
            httpBasic().and().
            csrf().disable();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
}

@Bean
protected UserDetailsService userDetailsService() {
    return new UserDetailsService() {

        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            Customer customer = customerRepository.findByUsername(username);
            if(user != null) {
                return new User(username, customer.getPassword(), true, true, true, true,
                        AuthorityUtils.createAuthorityList("USER"));
            } else {
                throw new UsernameNotFoundException("could not find the user '"
                        + username + "'");
            }
        }
    };
}
}

就像我说的,如果我删除密码编码器(来自AuthenticationManagerBuilder和Customer实体),输入用户名和密码将进行身份验证。但是,当我添加BCryptPasswordEncoder时,它不会进行身份验证,也不会给出错误消息。

1 个答案:

答案 0 :(得分:0)

请勿在实体的set方法中对密码进行编码。你只需要在创建新用户时这样做。 Spring安全将处理其余的问题