Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:


1. Overview

In this tutorial, we’ll discuss a critical part of the registration process, password encoding, which is basically not storing the password in plaintext.

There are a few encoding mechanisms supported by Spring Security, and for this tutorial, we’ll use BCrypt, as it’s usually the best solution available.

Most of the other mechanisms, such as the MD5PasswordEncoder and ShaPasswordEncoder, use weaker algorithms and are now deprecated.

Further reading:

New Password Storage in Spring Security 5

A quick guide to understanding password encryption in Spring Security 5 and migrating to better encryption algorithms.

Allow Authentication from Accepted Locations Only with Spring Security

Learn how to only allow users to authenticate from accepted locations only with Spring Security.

Spring Security - Auto Login User After Registration

Learn how to quickly auto-authenticate a user after they complete the registration process.

2. Define the Password Encoder

We’ll start by defining the simple BCryptPasswordEncoder as a bean in our configuration:

public PasswordEncoder encoder() {
    return new BCryptPasswordEncoder();

Older implementations, such as SHAPasswordEncoder, require the client to pass in a salt value when encoding the password.

BCrypt, however, will internally generate a random salt instead. This is important to understand because it means that each call will have a different result, so we only need to encode the password once.

To make this random salt generation work, BCrypt will store the salt inside the hash value itself. For instance, the following hash value:


Separates three fields by $:

  1. The “2a” represents the BCrypt algorithm version
  2. The “10” represents the strength of the algorithm
  3. The “ZLhnHxdpHETcxmtEStgpI.” part is actually the randomly generated salt. Basically, the first 22 characters are salt. The remaining part of the last field is the actual hashed version of the plain text.

Also, be aware that the BCrypt algorithm generates a String of length 60, so we need to make sure that the password will be stored in a column that can accommodate it. A common mistake is to create a column of a different length, and then get an Invalid Username or Password error at authentication time.

3. Encode the Password on Registration

We’ll use the PasswordEncoder in our UserService to hash the password during the user registration process:

Example 3.1. The UserService Hashes the Password

private PasswordEncoder passwordEncoder;

public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
    if (emailExist(accountDto.getEmail())) {
        throw new EmailExistsException(
          "There is an account with that email adress:" + accountDto.getEmail());
    User user = new User();
    user.setRole(new Role(Integer.valueOf(1), user));

4. Encode the Password on Authentication

Now we’ll handle the other half of this process and encode the password when the user authenticates.

First, we need to inject the password encoder bean we defined earlier into our authentication provider:

private UserDetailsService userDetailsService;

public DaoAuthenticationProvider authProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    return authProvider;

The security configuration is simple:

  • we inject our implementation of the users details service
  • we define an authentication provider that references our details service
  • we also enable the password encoder

Finally, we need to reference this auth provider in our security XML configuration:

    <authentication-provider ref="authProvider" />

Or, if we’re using Java configuration:

@ComponentScan(basePackages = { "" })
public class SecSecurityConfig {

    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)

5. Conclusion

This brief article continues the Registration series by showing how to properly store the password in the database by leveraging the simple, but very powerful, BCrypt implementation.

The full implementation of this Registration with Spring Security article can be found over on GitHub.

Next »
The Registration API becomes RESTful
« Previous
Spring Security Registration – Resend Verification Email
Course – LSS (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:


res – Security (video) (cat=Security/Spring Security)