DEV Community

Vadym Dudnyk
Vadym Dudnyk

Posted on

Password encoder in Spring Boot 2

Hi, Since Spring boot 2.x there was a few changes in Spring Security, so, I will show you how to encode passwords in Spring boot 2 (which comes with new Spring Security 5).

Most important change:

DelegatingPasswordEncoder it's the new default password encoder (which not tie you to a specific encoder implementation, like BcryptPasswordEncoder)

NoOpPasswordEncoder is considered as deprecated now.

  • How to create password encoder bean:
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
  • How to encode a password (Bcrypt implementation will be used underneath):
        String encodedPassword = passwordEncoder.encode(rawPassword);
  • How the encoded password looks like:

{bcrypt}$2a$10$GJpYuiP0cDOcE.WRlctpHOC1ROz35m9jCJ5BXFoMgnzkUjsxc6yHS
Where '{bcrypt}' determines which encoder used for encoding.

  • How to check if raw password matches encoded:
    if (!passwordEncoder.matches(rawPassword, encodedPassword)) {
        throw new BadCredentialsException("Bad password");
    }

Top comments (1)

Collapse
 
aliaksandradzinets profile image
Aliaksandr Adzinets • Edited

Hi Vadym. Nice article, thanks! Short, but clear about why use DelegatingPasswordEncoder and how to use it.