M
M
Maxim Rybalkin2020-12-30 11:53:38
Java
Maxim Rybalkin, 2020-12-30 11:53:38

How to encrypt password via BCrypt to H2 or HSQLDB database?

I'm using an H2 database (HSQLDB is allowed), a Spring Boot 2 project with the following config:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder(8);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/registration", "/activate/*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

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

There is a data.sql file that does insert at startup:
insert into users (email, username, password)
values ('[email protected]', 'admin', 'admin'),
       ('[email protected]', 'user', 'password'),
       ('[email protected]', 'user2', 'password');

insert into user_role (user_id, roles)
values (100000, 'ADMIN'),
       (100000, 'USER'),
       (100001, 'USER'),
       (100002, 'USER');

At the moment, when trying to authorize through these users, I get an error - Encoded password does not look like BCrypt
I need to either encrypt these passwords through BCrypt, or completely rewrite the encryption scheme. Tell me - how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mystifier, 2020-12-31
@mystifier

You can separately run somewhere the definition of hashes for the necessary passwords.
And then insert the desired hash into insert.
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(8);
String hashedAdmin = passwordEncoder.encode("admin");
String hashedPassword = passwordEncoder.encode("password");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question