Skip to content

Commit

Permalink
Use new DefaultOauth2User constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
andreblanke committed Dec 8, 2024
1 parent 77ce154 commit efbc5fe
Show file tree
Hide file tree
Showing 17 changed files with 56 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -711,8 +711,8 @@ private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantReque

private static OAuth2UserService<OAuth2UserRequest, OAuth2User> createOauth2UserService() {
Map<String, Object> userAttributes = Collections.singletonMap("name", "spring");
return (request) -> new DefaultOAuth2User(Collections.singleton(new OAuth2UserAuthority(userAttributes)),
userAttributes, "name");
return (request) -> new DefaultOAuth2User("spring", userAttributes,
Collections.singleton(new OAuth2UserAuthority(userAttributes)));
}

private static OAuth2UserService<OidcUserRequest, OidcUser> createOidcUserService() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,8 @@ public void oauth2LoginWhenOauth2UserServiceBeanPresent() {
given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> userService = config.reactiveOAuth2UserService;
given(userService.loadUser(any())).willReturn(Mono
.just(new DefaultOAuth2User(AuthorityUtils.createAuthorityList("USER"), Map.of("sub", "subject"), "sub")));
.just(new DefaultOAuth2User("subject", Map.of("sub", "subject"),
AuthorityUtils.createAuthorityList("USER"))));
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection();
verify(userService).loadUser(any());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class RedirectionEndpointDslTests {
.build()
every {
UserServiceConfig.USER_SERVICE.loadUser(any())
} returns DefaultOAuth2User(listOf(SimpleGrantedAuthority("ROLE_USER")), mapOf(Pair("user", "user")), "user")
} returns DefaultOAuth2User("user", mapOf(Pair("user", "user")), listOf(SimpleGrantedAuthority("ROLE_USER")))

this.mockMvc.get("/callback") {
param("code", "auth-code")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class UserInfoEndpointDslTests {
.build()
every {
UserServiceConfig.USER_SERVICE.loadUser(any())
} returns DefaultOAuth2User(listOf(SimpleGrantedAuthority("ROLE_USER")), mapOf(Pair("user", "user")), "user")
} returns DefaultOAuth2User("user", mapOf(Pair("user", "user")), listOf(SimpleGrantedAuthority("ROLE_USER")))

this.mockMvc.get("/login/oauth2/code/google") {
param("code", "auth-code")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
OAuth2AccessToken token = userRequest.getAccessToken();
Map<String, Object> attributes = this.attributesConverter.convert(userRequest).convert(response.getBody());
Collection<GrantedAuthority> authorities = getAuthorities(token, attributes, userNameAttributeName);
return new DefaultOAuth2User(authorities, attributes, userNameAttributeName);
return new DefaultOAuth2User(attributes.get(userNameAttributeName).toString(), attributes, authorities);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2Aut
authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
}

return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
return new DefaultOAuth2User(attrs.get(userNameAttributeName).toString(), attrs, authorities);
})
.onErrorMap((ex) -> (ex instanceof UnsupportedMediaTypeException ||
ex.getCause() instanceof UnsupportedMediaTypeException), (ex) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ public void authenticationWhenOAuth2UserFoundThenSuccess() {
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
DefaultOAuth2User user = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken())
.block();
Expand All @@ -177,8 +177,8 @@ public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToU
.additionalParameters(additionalParameters)
.build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
DefaultOAuth2User user = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
this.manager.authenticate(loginToken()).block();
Expand All @@ -192,8 +192,8 @@ public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
DefaultOAuth2User user = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ public void loadUserWhenOAuth2UserEmptyThenNullUserInfo() {

@Test
public void loadUserWhenOAuth2UserSubjectNullThenOAuth2AuthenticationException() {
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
OAuth2User oauth2User = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest()).block());
Expand All @@ -151,8 +151,8 @@ public void loadUserWhenOAuth2UserSubjectNotEqualThenOAuth2AuthenticationExcepti
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "not-equal");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
OAuth2User oauth2User = new DefaultOAuth2User("rob", attributes,
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest()).block());
Expand All @@ -163,8 +163,8 @@ public void loadUserWhenOAuth2UserThenUserInfoNotNull() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
OAuth2User oauth2User = new DefaultOAuth2User("rob", attributes,
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThat(this.userService.loadUser(userRequest()).block().getUserInfo()).isNotNull();
}
Expand All @@ -175,8 +175,8 @@ public void loadUserWhenOAuth2UserAndUser() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
OAuth2User oauth2User = new DefaultOAuth2User("rob", attributes,
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThat(this.userService.loadUser(userRequest()).block().getName()).isEqualTo("rob");
}
Expand All @@ -186,8 +186,8 @@ public void loadUserWhenCustomClaimTypeConverterFactorySetThenApplied() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "rob");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
OAuth2User oauth2User = new DefaultOAuth2User("rob", attributes,
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
OidcUserRequest userRequest = userRequest();
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(
Expand Down Expand Up @@ -220,8 +220,8 @@ public void loadUserWhenCustomRetrieveUserInfoSetThenUsed() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "steve");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
OAuth2User oauth2User = new DefaultOAuth2User("steve", attributes,
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
Predicate<OidcUserRequest> customRetrieveUserInfo = mock(Predicate.class);
this.userService.setRetrieveUserInfo(customRetrieveUserInfo);
Expand All @@ -246,8 +246,8 @@ public void loadUserWhenCustomOidcUserMapperSetThenUsed() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "steve");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
OAuth2User oauth2User = new DefaultOAuth2User("steve", attributes,
AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.oauth2UserService.loadUser(any(OidcUserRequest.class))).willReturn(Mono.just(oauth2User));
BiFunction<OidcUserRequest, OidcUserInfo, Mono<OidcUser>> customOidcUserMapper = mock(BiFunction.class);
OidcUser actualUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("a", "b"), this.idToken,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public void setUp() {
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, "user", accessToken);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("OAUTH2_USER");
Map<String, Object> attributes = Map.of(StandardClaimNames.SUB, "user");
OAuth2User user = new DefaultOAuth2User(authorities, attributes, StandardClaimNames.SUB);
OAuth2User user = new DefaultOAuth2User("user", attributes, authorities);
this.principal = new OAuth2AuthenticationToken(user, authorities, "login-client");
this.requestInterceptor = new OAuth2ClientHttpRequestInterceptor(this.authorizedClientManager);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,8 @@ public void filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClient
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
.willReturn(Mono.just(authorizedClient));
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
OAuth2User user = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(),
"client-id");
this.function.filter(request, this.exchange)
Expand All @@ -828,8 +828,8 @@ public void filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClient
@Test
public void filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
OAuth2User user = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(),
"client-id");
// @formatter:off
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ public void onAuthenticationSuccessWhenOAuth2LoginAuthenticationTokenThenSavesAu
private OAuth2LoginAuthenticationToken loginToken() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token",
Instant.now(), Instant.now().plus(Duration.ofDays(1)), Collections.singleton("user"));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
DefaultOAuth2User user = new DefaultOAuth2User("rob", Collections.singletonMap("user", "rob"),
AuthorityUtils.createAuthorityList("ROLE_USER"));
ClientRegistration clientRegistration = this.registration.build();
// @formatter:off
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ public class DefaultOAuth2UserTests {
@Test
public void constructorWhenAttributesIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultOAuth2User(AUTHORITIES, null, ATTRIBUTE_NAME_KEY));
.isThrownBy(() -> new DefaultOAuth2User(USERNAME, null, AUTHORITIES));
}

@Test
public void constructorWhenAttributesIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultOAuth2User(AUTHORITIES, Collections.emptyMap(), ATTRIBUTE_NAME_KEY));
.isThrownBy(() -> new DefaultOAuth2User(USERNAME, Collections.emptyMap(), AUTHORITIES));
}

@Test
Expand All @@ -82,23 +82,23 @@ public void constructorWhenNameAttributeKeyIsInvalidThenThrowIllegalArgumentExce

@Test
public void constructorWhenAuthoritiesIsNullThenCreatedWithEmptyAuthorities() {
DefaultOAuth2User user = new DefaultOAuth2User(null, ATTRIBUTES, ATTRIBUTE_NAME_KEY);
DefaultOAuth2User user = new DefaultOAuth2User(USERNAME, ATTRIBUTES, null);
assertThat(user.getName()).isEqualTo(USERNAME);
assertThat(user.getAuthorities()).isEmpty();
assertThat(user.getAttributes()).containsOnlyKeys(ATTRIBUTE_NAME_KEY);
}

@Test
public void constructorWhenAuthoritiesIsEmptyThenCreated() {
DefaultOAuth2User user = new DefaultOAuth2User(Collections.emptySet(), ATTRIBUTES, ATTRIBUTE_NAME_KEY);
DefaultOAuth2User user = new DefaultOAuth2User(USERNAME, ATTRIBUTES, Collections.emptySet());
assertThat(user.getName()).isEqualTo(USERNAME);
assertThat(user.getAuthorities()).isEmpty();
assertThat(user.getAttributes()).containsOnlyKeys(ATTRIBUTE_NAME_KEY);
}

@Test
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
DefaultOAuth2User user = new DefaultOAuth2User(AUTHORITIES, ATTRIBUTES, ATTRIBUTE_NAME_KEY);
DefaultOAuth2User user = new DefaultOAuth2User(USERNAME, ATTRIBUTES, AUTHORITIES);
assertThat(user.getName()).isEqualTo(USERNAME);
assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities().iterator().next()).isEqualTo(AUTHORITY);
Expand All @@ -108,7 +108,7 @@ public void constructorWhenAllParametersProvidedAndValidThenCreated() {
// gh-4917
@Test
public void constructorWhenCreatedThenIsSerializable() {
DefaultOAuth2User user = new DefaultOAuth2User(AUTHORITIES, ATTRIBUTES, ATTRIBUTE_NAME_KEY);
DefaultOAuth2User user = new DefaultOAuth2User(USERNAME, ATTRIBUTES, AUTHORITIES);
SerializationUtils.serialize(user);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static DefaultOAuth2User create() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(nameAttributeKey, "user");
Collection<GrantedAuthority> authorities = authorities(attributes, nameAttributeKey);
return new DefaultOAuth2User(authorities, attributes, nameAttributeKey);
return new DefaultOAuth2User("user", attributes, authorities);
}

private static Collection<GrantedAuthority> authorities(Map<String, Object> attributes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,8 @@ private Map<String, Object> defaultAttributes() {
}

private OAuth2User defaultPrincipal() {
return new DefaultOAuth2User(this.authorities.get(), this.attributes.get(), this.nameAttributeKey);
String name = this.attributes.get().get(this.nameAttributeKey).toString();
return new DefaultOAuth2User(name, this.attributes.get(), this.authorities.get());
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1390,7 +1390,8 @@ private Map<String, Object> defaultAttributes() {
}

private OAuth2User defaultPrincipal() {
return new DefaultOAuth2User(this.authorities.get(), this.attributes.get(), this.nameAttributeKey);
String name = this.attributes.get().get(this.nameAttributeKey).toString();
return new DefaultOAuth2User(name, this.attributes.get(), this.authorities.get());
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,9 @@ public void oauth2LoginWhenAttributeSpecifiedThenUserHasAttribute() {

@Test
public void oauth2LoginWhenNameSpecifiedThenUserHasName() throws Exception {
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"),
Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute");
OAuth2User oauth2User = new DefaultOAuth2User("test-subject",
Collections.singletonMap("custom-attribute", "test-subject"),
AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"));
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User))
.get()
.uri("/token")
Expand All @@ -155,8 +156,8 @@ public void oauth2LoginWhenNameSpecifiedThenUserHasName() throws Exception {

@Test
public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"),
Collections.singletonMap("sub", "subject"), "sub");
OAuth2User oauth2User = new DefaultOAuth2User("subject", Collections.singletonMap("sub", "subject"),
AuthorityUtils.createAuthorityList("SCOPE_read"));
this.client
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
.attributes((a) -> a.put("subject", "foo"))
Expand Down
Loading

0 comments on commit efbc5fe

Please sign in to comment.