DEV Community

Vadym Dudnyk
Vadym Dudnyk

Posted on

11 2

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");
    }

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
aliaksandradzinets profile image

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

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay