I'm trying to use a DelegatingPasswordEncoder with jdbcAuthentication()
. However, when I try to do this it gives me an HTTP status of 403. But when I do this with inMemoryAuthentication()
, it works fine. Can anyone explain a reason why this is happening? Any mistakes that I'm doing?
I'm using bcrypt as the encoder and the passwords are stored in the database prefixed with the algorithm id like in the example below.
{bcrypt}$2a$10$t1E8PjjYqqp0Uovp6jVgS.r7J7yNzoH0pV3egIbzqQta0yznloJcG
ApplicationSecurityConfig.java
@Configuration
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AppConfigProperties acp;
@Autowired
private DataSource dataSource;
@Autowired
private ApplicationUserRepo appUserRepo;
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String idForEncode = acp.getApplicationEncoding();
Map encoders = new HashMap<>();
encoders.put("bcrypt", new BCryptPasswordEncoder());
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("sha256", new StandardPasswordEncoder());
PasswordEncoder pwEncoder = new DelegatingPasswordEncoder(idForEncode, encoders);
/*System.out.println(pwEncoder.encode("gad"));
System.out.println(new BCryptPasswordEncoder().encode("gad"));
Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("select password from application_user where user_name='gad'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(new BCryptPasswordEncoder().matches("gad", rs.getString(1)));
}*/
auth.jdbcAuthentication().dataSource(dataSource)
.passwordEncoder(pwEncoder)
.usersByUsernameQuery("select user_name, password, enabled from application_user where user_name=?")
.authoritiesByUsernameQuery("select user_name, user_role from application_user_roles where user_name=?");
/*auth.inMemoryAuthentication().passwordEncoder(pwEncoder)
.withUser("gad").password(pwEncoder.encode("gad")).roles("USER")
.and()
.withUser("admin").password(pwEncoder.encode("admin")).roles("ADMIN");*/
}
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/welcome/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/**").hasRole("ADMIN")
.and()
.csrf().disable().headers().frameOptions().disable()
.and()
.exceptionHandling().accessDeniedPage("/accessDenied");
}
}