๐ช๐ต๐ ๐ฌ๐ผ๐ ๐ก๐ฒ๐ฒ๐ฑ ๐ฃ๐ฎ๐๐๐๐ผ๐ฟ๐ฑ๐๐ป๐ฐ๐ผ๐ฑ๐ฒ๐ฟ ๐ถ๐ป ๐ฆ๐ฝ๐ฟ๐ถ๐ป๐ด ๐ฆ๐ฒ๐ฐ๐๐ฟ๐ถ๐๐
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:
Registration: You take the raw password. You run it through the encoder. You save the encoded string to your database.
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