- Spring Security(Third Edition)
- Mick Knutson Robert Winch Peter Mularien
- 159字
- 2025-04-04 17:54:29
Hashing the stored passwords
As illustrated in the following diagram, when a user submits a password, Spring Security hashes the submitted password and then compares that against the unhashed password in the database:

This means that users cannot log in to our application. To fix this, we will update the SQL that is loaded at startup time to update the passwords to be the hashed values. Update the DataSourceConfig.java file, as follows:
//src/main/java/com/packtpub/springsecurity/configuration/DataSourceConfig.java
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setName("dataSource")
.setType(EmbeddedDatabaseType.H2)
.addScript("/database/h2/calendar-schema.sql")
.addScript("/database/h2/calendar-data.sql")
.addScript("/database/h2/calendar-authorities.sql")
.addScript("/database/h2/calendar-sha256.sql")
.build();
}
The calendar-sha256.sql file simply updates the existing passwords to their expected hashed values, as follows:
update calendar_users set password =
'0a041b9462caa4a31bac3567e0b6e6fd9100787db2ab433d96f6d178cabfce90'
where email = 'user1@example.com';
How did we know what value to update the password to? We have provided o.s.s.authentication.encoding.Sha256PasswordEncoderMain to demonstrate how to use the configured PasswordEncoder interface to hash the existing passwords. The relevant code is as follows:
ShaPasswordEncoder encoder = new ShaPasswordEncoder(256);
String encodedPassword = encoder.encodePassword(password, null);