๐—ช๐—ต๐˜† ๐—ฌ๐—ผ๐˜‚ ๐—ก๐—ฒ๐—ฒ๐—ฑ ๐—ฃ๐—ฎ๐˜€๐˜€๐˜„๐—ผ๐—ฟ๐—ฑ๐—˜๐—ป๐—ฐ๐—ผ๐—ฑ๐—ฒ๐—ฟ ๐—ถ๐—ป ๐—ฆ๐—ฝ๐—ฟ๐—ถ๐—ป๐—ด ๐—ฆ๐—ฒ๐—ฐ๐˜‚๐—ฟ๐—ถ๐˜๐˜†

You might ask why Spring Security needs a PasswordEncoder. If the system checks usernames and passwords, why not store them directly?

Storing plain text passwords is a mistake.

If a hacker steals your database, they see every password. A user with the password sonali123 becomes an easy target.

You must store an encoded version instead.

An encoded password looks like this: $2a$10$k9Y...

Even if a hacker accesses your database, they do not see the actual password.

Spring Security uses the PasswordEncoder interface to manage this. Most developers use BCryptPasswordEncoder.

You set it up with a simple bean:

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

The process works in two steps:

  1. Registration: You take the raw password. You run it through the encoder. You save the encoded string to your database.

  2. Login: The user enters their password. Spring Security pulls the encoded password from the database. The system uses passwordEncoder.matches() to check them.

You do not compare the strings directly. BCrypt creates a different hash every time. This makes your system harder to crack.

The logic follows this path: User enters password Spring fetches encoded password PasswordEncoder.matches() runs the check Login succeeds or fails

Never store plain text passwords. Use PasswordEncoder to protect your users.

Source: https://dev.to/sonalishahi/-why-do-we-use-passwordencoder-in-spring-security-3klo