User.UserBuilder only encodes once

Fixes gh-4794
This commit is contained in:
Rob Winch 2017-11-06 09:27:03 -06:00
parent 21aec19d42
commit d9abd2e443
2 changed files with 18 additions and 4 deletions

View File

@ -323,8 +323,7 @@ public class User implements UserDetails, CredentialsContainer {
*/
public UserBuilder password(String password) {
Assert.notNull(password, "password cannot be null");
String encodedPassword = this.passwordEncoder.apply(password);
this.password = encodedPassword;
this.password = password;
return this;
}
@ -339,7 +338,7 @@ public class User implements UserDetails, CredentialsContainer {
public UserBuilder passwordEncoder(Function<String,String> encoder) {
Assert.notNull(encoder, "encoder cannot be null");
this.passwordEncoder = encoder;
return this.password == null ? this : password(this.password);
return this;
}
/**
@ -467,7 +466,8 @@ public class User implements UserDetails, CredentialsContainer {
}
public UserDetails build() {
return new User(username, password, !disabled, !accountExpired,
String encodedPassword = this.passwordEncoder.apply(password);
return new User(username, encodedPassword, !disabled, !accountExpired,
!credentialsExpired, !accountLocked, authorities);
}
}

View File

@ -23,6 +23,7 @@ import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.junit.Test;
import org.springframework.security.core.GrantedAuthority;
@ -210,4 +211,17 @@ public class UserTests {
assertThat(withEncodedPassword.getPassword()).isEqualTo("passwordencoded");
}
@Test
public void withUsernameWhenPasswordAndPasswordEncoderTwiceThenEncodesOnce() {
Function<String, String> encoder = p -> p + "encoded";
UserDetails withEncodedPassword = User.withUsername("user")
.passwordEncoder(encoder)
.password("password")
.passwordEncoder(encoder)
.roles("USER")
.build();
assertThat(withEncodedPassword.getPassword()).isEqualTo("passwordencoded");
}
}