How can I encrypt a password coming from application.properties
?
spring:
security:
user:
name: bob
password: alice
Spring security authentication:
@Configuration
@EnableWebSecurity
public class BasicAuthConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.anyRequest().authenticated()
)
.httpBasic();
return http.build();
}
//TODO: Not working
//@Bean
// public PasswordEncoder passwordEncoder() {
//return new BCryptPasswordEncoder(10);
//}
}
I assume passwordEncoder()
is called and encrypts the password.
(EDIT: If not, how can I access the properties password so I can call the passwordEncoder explicitly?)
But when I try to make a basic authentication
request using raw password(bob:alice) it doesn't work.
I'm getting 401
and Spring log is Encoded password does not look like BCrypt
.
How can I encrypt my password and also allow clients to make requests with raw credentials?
CodePudding user response:
Keep the PasswordEncoder bean, and put in properties the password encoded by your encoder (not the raw password).
So in your case sth. like this:
spring:
security:
user:
name: bob
password: $2a$10$2T4wM24pGyHuLj12SI/rC.C1gkg4mLGTuzTse3choIVIOtlgsWmPC
CodePudding user response:
Uncomment your password encoder bean. Then temporarily use the password encoder to encode your plaintext password. Log or print the encoded password. Then replace the password in your application properties with the encrypted password. You can encrypt your plaintext password by calling the following method:
var encodedPassword = passwordEncoder.encode(rawPassword);
Don't forget to remove the code that you used to temporarily log/print your encoded password.