OidcUserService uses custom userNameAttributeName

Fixes gh-4812
This commit is contained in:
Joe Grandja 2017-11-12 14:44:57 -05:00
parent 3661cb58d6
commit 426c034c01
2 changed files with 44 additions and 1 deletions

View File

@ -78,7 +78,17 @@ public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcU
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(authority);
return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
OidcUser user;
String userNameAttributeName = userRequest.getClientRegistration()
.getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
if (StringUtils.hasText(userNameAttributeName)) {
user = new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName);
} else {
user = new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
}
return user;
}
private boolean shouldRetrieveUserInfo(OidcUserRequest userRequest) {

View File

@ -35,6 +35,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
@ -257,4 +258,36 @@ public class OidcUserServiceTests {
this.userService.loadUser(new OidcUserRequest(this.clientRegistration, this.accessToken, this.idToken));
}
@Test
public void loadUserWhenCustomUserNameAttributeNameThenGetNameReturnsCustomUserName() throws Exception {
MockWebServer server = new MockWebServer();
String userInfoResponse = "{\n" +
" \"sub\": \"subject1\",\n" +
" \"name\": \"first last\",\n" +
" \"given_name\": \"first\",\n" +
" \"family_name\": \"last\",\n" +
" \"preferred_username\": \"user1\",\n" +
" \"email\": \"user1@example.com\"\n" +
"}\n";
server.enqueue(new MockResponse()
.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.setBody(userInfoResponse));
server.start();
String userInfoUri = server.url("/user").toString();
when(this.userInfoEndpoint.getUri()).thenReturn(userInfoUri);
when(this.userInfoEndpoint.getUserNameAttributeName()).thenReturn(StandardClaimNames.EMAIL);
when(this.accessToken.getTokenValue()).thenReturn("access-token");
OidcUser user = this.userService.loadUser(
new OidcUserRequest(this.clientRegistration, this.accessToken, this.idToken));
server.shutdown();
assertThat(user.getName()).isEqualTo("user1@example.com");
}
}