You know, by default Spring Security requires passwords to be encoded using a specific password encoder, e.g. BCryptPasswordEncoder, which is declared in the security configuration class like this:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { ... } }
What if you want to use plain text password for quickly testing in development? If so, you can use NoOpPasswordEncoder as shown below:
@Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); }
Then you can login using plain text password stored in database, without password encoding.
The NoOpPasswordEncoder does not encode password, and just compares equality of two Strings, thus you can use plain text password for users. And note that Spring marks it deprecated - indicating that it is insecure and should be used for testing purposes only.
If you don’t want to see the deprecated warning message, you can create your own password encoder, as shown below:
package net.codejava; import org.springframework.security.crypto.password.PasswordEncoder; public class PlainTextPasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence rawPassword) { return rawPassword.toString(); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return rawPassword.toString().equals(encodedPassword); } public static PasswordEncoder getInstance() { return INSTANCE; } private static final PasswordEncoder INSTANCE = new PlainTextPasswordEncoder(); private PlainTextPasswordEncoder() { } }
This code is as same as code of the NoOpPasswordEncoder class, without deprecation warning. Then declare it in the security configuration class as follows:
@Bean public PasswordEncoder passwordEncoder() { return PlainTextPasswordEncoder.getInstance(); }
That’s a simple tip which you can use to use plain text password in Spring-based application with Spring Security. Remember that doing so for testing purposes only. In production, you should use a strong password encoder.