In a previous post, we used the user details service in order to provide a way to load our data from a function based on a username given.

The implementation of the user details might be backed by an in-memory mechanism, a SQL/NoSQL database, etc.

The options are unlimited.

What we have to pay attention when it comes to password storage is the password hashing.For security reasons, we want to store passwords in a hashed form. Supposing someone gets unauthorized access to the table storing our user data, by storing the passwords in clear text, that person can retrieve the password of every user in the system.

So we want a way to hash our passwords before storing them in a database. Always be aware that your hashing has to be robust and up to date. For example, MD5 was very popular in the past but nowadays it leads to poor security. Actually, it is possible to crack MD5 passwords fairly easily if you use a gpu.

Spring Security provides us with out-of-the-box functionality when it comes to encoding passwords. Password encoder is an interface which is used through the authorization process.

The encode function shall be used to encode your password and the matches function will check if your raw password matches the encoded password. Once your user details service fetches the user information from the database then the password given to authorize shall be validated with the one fetched from the database. In this case, Spring will use the matches function.

Now Spring provides us with various implementations of a password encoder. Let's try to create a password encoder bean.

This bean is no different than the NoOpPasswordEncoder which comes with Spring Boot.

Now we are going to do a small experiment and add a custom password encoder. Our password encoder will compare the clear text password submitted by the user, hash it, and then compare it with an already hashed password from the equivalent user in our database.