EDIT:
The simplest way I found:
@SuppressWarnings("deprecation")
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
"SELECT username, password, abilitazione FROM public.utenti WHERE username=?")
.passwordEncoder(passwordEncoder())
.authoritiesByUsernameQuery(
"SELECT username, ruolo FROM public.ruoli_utente WHERE username=?");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//omitted for brevity
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
in my dao class I add users like this:
public void addElement(Utente u) {
String password = u.getPassword();
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
u.setPassword(hashedPassword);
jdbcTemplate.update("INSERT INTO public.utenti(username, password, abilitazione, email, nome, cognome) VALUES (?, ?, ?, ?, ?, ?)",
new Object[] {u.getUsername(), u.getPassword(), u.getAbilitazione(), u.getEmail(), u.getNome(), u.getCognome()});
}
I want to encrypt and decrypt the password in a super easy way, doesn't matter if it's not super secure, it just have to be secure for my purpose. So, in database I added encrypted passwords. When the user authenticate it doesn't recognize the password, even if I decode it. I did it like this:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
"SELECT username, decode(password,'base64'), abilitazione FROM public.utenti WHERE username=?")
.authoritiesByUsernameQuery(
"SELECT username, ruolo FROM public.ruoli_utente WHERE username=?");
}
}
It could work in similar ways (decoding directly in usersByUsernameQuery method), or I must declare some beans for decoding?