getRemoteUser() returns principal name

Closes gh-3357
This commit is contained in:
Stephen Joyner 2020-11-20 13:46:40 -06:00 committed by Josh Cummings
parent d5d0be36f4
commit 9c373ef4f8
No known key found for this signature in database
GPG Key ID: 49EF60DD7FF83443
2 changed files with 23 additions and 0 deletions

View File

@ -22,6 +22,7 @@ import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
@ -106,6 +107,9 @@ public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequest
if (auth.getPrincipal() instanceof UserDetails) {
return ((UserDetails) auth.getPrincipal()).getUsername();
}
if (auth.getPrincipal() instanceof AbstractAuthenticationToken) {
return ((AbstractAuthenticationToken) auth.getPrincipal()).getName();
}
return auth.getPrincipal().toString();
}

View File

@ -21,12 +21,17 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests {@link SecurityContextHolderAwareRequestWrapper}.
@ -130,4 +135,18 @@ public class SecurityContextHolderAwareRequestWrapperTests {
assertThat(wrapper.isUserInRole("ROLE_FOOBAR")).isTrue();
}
@Test
public void testGetRemoteUserStringWithAuthenticatedPrincipal() {
String username = "authPrincipalUsername";
AuthenticatedPrincipal principal = mock(AuthenticatedPrincipal.class);
given(principal.getName()).willReturn(username);
Authentication auth = new TestingAuthenticationToken(principal, "user");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/");
SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, "");
assertThat(wrapper.getRemoteUser()).isEqualTo(username);
verify(principal, times(1)).getName();
}
}