Search code examples
javaspringjakarta-eespring-securitybcrypt

BCrypt in my Spring Security project (Spring security)


how can I do encryption. So that in the database it does not show the user password. I am now saved in the database - login and password, user role. I need Password must be encrypted (BCrypt) in the database

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/allStudents")
                .and()
                .logout()
                .and()
                .csrf().disable();
    }

    @Bean
    public PasswordEncoder weDoNotWantEncryption() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return rawPassword.toString().equals(encodedPassword);
            }
        };
    }

}

Solution

  • Very simply - just replace your weDoNotWantEncryption() function with one that returns a BCrypt instance:

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

    BCryptPasswordEncoder implements PasswordEncoder (as the name suggests) and so already has good methods defined for encode() and matches().

    Note that this will (of course) render any passwords currently in your database unusable, although given that those passwords are stored in plaintext, I assume (and hope/pray) that this is in a test environment, rather than production.