我正在用Java和Spring创建一个Web应用程序。我正在使用Java JDK 12,Sping Boot 2.1.6,Spring Security 5和Thymeleaf 3.0.11。
我使用SpringSecurity进行用户身份验证。我想将用户数据(用户名、密码等)存储在MySQL数据库中。
我已经在数据库中创建了一个用户,并用BCrypt加密了密码。
当我尝试使用我的登录表单登录时,我收到消息“编码密码看起来不像BCrypt”。
我认为问题是,我必须实现BCryptPasswordEncoder。
我已经尝试了Stackoverflow和其他网站上的所有其他帖子,但是我不明白如何实现密码编码器以使用MySQL数据库。
SpringSecurity.class
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Autowired
private DataSource dataSource;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
"select username, password, enabled from users where username=?")
.authoritiesByUsernameQuery(
"select username, role from user_roles where username=?");
}
}
您应该在配置身份验证
方法上指定密码加密。看看这个例子:
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder()).dataSource(dataSource)
.usersByUsernameQuery(usernameQuery)
.authoritiesByUsernameQuery(authoritiesQuery);
}
只需添加引用 BCryptPasswordEncoder 的 passwordEncoder
配置,您还可以定义一个自定义 Bean 来处理该加密。