PasswordEncoder

Before Spring Security 5, the framework allowed only one PasswordEncoder throughout the application and also had weak password encoders such as MD5 and SHA. These encoders also didn't have dynamic salt, rather it had more static salt which had to be supplied. With Spring Security 5, there have been huge changes in this area and with the new version, the password encoding concept employs delegation and allows multiple password encoding within the same application. The password which has been encoded has a identifier prefixed to indicate what algorithm has been used (see the following example):

{bcrypt}$2y$10$zsUaFDpkjg01.JVipZhtFeOHpC2/LCH3yx6aNJpTNDOA8zDqhzgR6

This approach enables multiple encoding as needed within the application to be employed. If no identifier is mentioned, this means it uses the default encoder, which is StandardPasswordEncoder.

Once you decide on the password encoding, this can be used within the AuthenticationManager. One such example is the following code snippet:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(new StandardPasswordEncoder())
.withUser("user")
.password("025baf3868bc8f785267d4aec1f02fa50809b7f715576198eda6466")
.roles("USER");
}

Spring Security 5, as mentioned earlier, introduced a delegation approach by introducing DelegationPasswordEncoder. DelegatingPasswordEncoder has replaced PasswordEncoder and can be created by two approaches as follows:

  • Approach 1:
PasswordEncoder passwordEncoder = 
PasswordEncoderFactories.createDelegatingPasswordEncoder();
passwordEncoder.setDefaultPasswordEncoderForMatches(new BCryptPasswordEncoder());
  • Approach 2:
String defaultEncode = "bcrypt";
Map encoders = new HashMap<>();
encoders.put(defaultEncode, new BCryptPasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("sha256", new StandardPasswordEncoder());

PasswordEncoder passwordEncoder =
new DelegatingPasswordEncoder(defaultEncode, encoders);

DelegatingPasswordEncoder allows passwords to be validated against old encoding approaches and upgrades the password over a period of time without any hassle. This approach can be used to automatically upgrade passwords (old encoding to new encoding) as and when the user authenticates.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.152.166