[英]BcryptEncoder configuration in Spring Security Configuration
所以我正在创建这个restservice,但我在编码器配置上苦苦挣扎。
我创建了一个配置类来设置 passwordencoderBean,如下面的回复中所述。
我的代码编译。 但是当我尝试登录时,我得到“错误凭据”,是的,我确信我使用了正确的凭据。 也是的,我的数据库中的密码是 Bcryptencoded,前面有 {bcrypt}。 我的猜测是我错误配置了这个passwordEncoder配置。配置错误在哪里?
下面是我的密码编码配置:
@Configuration
public class PasswordEncoderConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
当前的 SpringSecurityConfiguration:
@EnableWebSecurity
class SecurityConfiguration extends WebSecurityConfigurerAdapter{
private static final String ADMIN = "ROLE_ADMIN";
private static final String WORKER = "ROLE_WORKER";
private final DataSource dataSource;
private PasswordEncoder bcryptencoder;
public SecurityConfiguration(DataSource dataSource, PasswordEncoder bcryptencoder) {
this.dataSource = dataSource;
this.bcryptencoder = bcryptencoder;
}
/*@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select voornaam as username, password as password, true as enabled from gebruikers where voornaam = ?")
.passwordEncoder(bcryptencoder)
.authoritiesByUsernameQuery("select voornaam as username, role as authorities from gebruikers where voornaam = ?");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.mvcMatchers("/images/**")
.mvcMatchers("/css/**")
.mvcMatchers("/js/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
/*remove after postman, @cross origin*/
http.formLogin();
http.authorizeHttpRequests(requests -> requests
.mvcMatchers("/**").hasAnyAuthority(ADMIN, WORKER)
.mvcMatchers("/gebruikers/**").hasAnyAuthority(ADMIN, WORKER));
http.logout();
}
}
方法是使用
@Bean
public PasswordEncoder passwordEncoder()
{
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
它使用 BCrypt 作为默认值,但为将来的迁移提供了更好的界面。 请注意,生成的密码有一个前缀:
With Factory:
{bcrypt}$2a$10$Zz3xIJON0d1GI0vqMULIKOHCImVnFCWMNRE3Vw0ElvSmfCqGcDV5W
Without:
$2a$10$Zz3xIJON0d1GI0vqMULIKOHCImVnFCWMNRE3Vw0ElvSmfCqGcDV5W
当您使用工厂并提供不带前缀的 bcrypt 哈希时,它将被视为无效而被拒绝。
编辑:正如 Chaosfire 所说,您定义了一个圆形 bean 定义。 您可以使用 bean 声明的方法而不是将其注入到字段中,spring 会将实例注入到方法调用中,因此您最终会得到与您在 bean 声明中提供的相同的密码编码器。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select voornaam as username, password as password, true as enabled from gebruikers where voornaam = ?")
.passwordEncoder(passwordEncoder()) // referencing bean, not field
.authoritiesByUsernameQuery("select voornaam as username, role as authorities from gebruikers where voornaam = ?");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.