Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve custom user type in InMemoryUserDetailsManager #15498

Merged
merged 2 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -30,6 +30,7 @@
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.User;
Expand Down Expand Up @@ -96,7 +97,13 @@ private User createUserDetails(String name, UserAttribute attr) {
@Override
public void createUser(UserDetails user) {
Assert.isTrue(!userExists(user.getUsername()), "user should not exist");
this.users.put(user.getUsername().toLowerCase(), new MutableUser(user));

if (user instanceof MutableUserDetails mutable) {
this.users.put(user.getUsername().toLowerCase(), mutable);
}
else {
this.users.put(user.getUsername().toLowerCase(), new MutableUser(user));
}
}

@Override
Expand All @@ -107,7 +114,13 @@ public void deleteUser(String username) {
@Override
public void updateUser(UserDetails user) {
Assert.isTrue(userExists(user.getUsername()), "user should exist");
this.users.put(user.getUsername().toLowerCase(), new MutableUser(user));

if (user instanceof MutableUserDetails mutable) {
this.users.put(user.getUsername().toLowerCase(), mutable);
}
else {
this.users.put(user.getUsername().toLowerCase(), new MutableUser(user));
}
}

@Override
Expand Down Expand Up @@ -154,6 +167,9 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx
if (user == null) {
throw new UsernameNotFoundException(username);
}
if (user instanceof CredentialsContainer) {
return user;
}
return new User(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(),
user.isCredentialsNonExpired(), user.isAccountNonLocked(), user.getAuthorities());
}
jzheaux marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,19 +16,24 @@

package org.springframework.security.provisioning;

import java.util.Collection;
import java.util.Properties;

import org.junit.jupiter.api.Test;

import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
Expand Down Expand Up @@ -97,4 +102,91 @@ public void changePasswordWhenCustomSecurityContextHolderStrategyThenUses() {
verify(strategy).getContext();
}

@Test
public void createUserWhenUserAlreadyExistsThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.createUser(this.user))
.withMessage("user should not exist");
}

@Test
public void createUserWhenInstanceOfMutableUserDetailsThenChangePasswordWorks() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
CustomUser user = new CustomUser(User.withUserDetails(PasswordEncodedUser.user()).build());
Authentication authentication = TestAuthentication.authenticated(user);
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
manager.setSecurityContextHolderStrategy(strategy);
manager.createUser(user);
String newPassword = "newPassword";
manager.changePassword(user.getPassword(), newPassword);
assertThat(manager.loadUserByUsername(user.getUsername()).getPassword()).isEqualTo(newPassword);
}

@Test
public void updateUserWhenUserDoesNotExistThenException() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
assertThatIllegalArgumentException().isThrownBy(() -> manager.updateUser(this.user))
.withMessage("user should exist");
}

@Test
public void loadUserByUsernameWhenUserNullThenException() {
jzheaux marked this conversation as resolved.
Show resolved Hide resolved
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> manager.loadUserByUsername(this.user.getUsername()));
}

@Test
public void loadUserByUsernameWhenNotInstanceOfCredentialsContainerThenReturnInstanceOfCredentialsContainer() {
MutableUser user = new MutableUser(User.withUserDetails(PasswordEncodedUser.user()).build());
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(user);
assertThat(user).isNotInstanceOf(CredentialsContainer.class);
assertThat(manager.loadUserByUsername(user.getUsername())).isInstanceOf(CredentialsContainer.class);
}

@Test
public void loadUserByUsernameWhenInstanceOfCredentialsContainerThenReturnInstance() {
CustomUser user = new CustomUser(User.withUserDetails(PasswordEncodedUser.user()).build());
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(user);
assertThat(manager.loadUserByUsername(user.getUsername())).isSameAs(user);
}

static class CustomUser implements MutableUserDetails, CredentialsContainer {

private final UserDetails delegate;

private String password;

CustomUser(UserDetails user) {
this.delegate = user;
this.password = user.getPassword();
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.delegate.getAuthorities();
}

@Override
public String getPassword() {
return this.password;
}

@Override
public void setPassword(final String password) {
this.password = password;
}

@Override
public String getUsername() {
return this.delegate.getUsername();
}

@Override
public void eraseCredentials() {
this.password = null;
}

}

}