Skip to content

Commit

Permalink
Polish setAttributesConverter
Browse files Browse the repository at this point in the history
- Add Tests
- Add Reactive Support

Issue spring-projectsgh-14186
  • Loading branch information
jzheaux committed Jan 30, 2024
1 parent c6623a1 commit e3b5da6
Show file tree
Hide file tree
Showing 4 changed files with 148 additions and 4 deletions.
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 @@ -26,6 +26,7 @@
import reactor.core.publisher.Mono;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
Expand Down Expand Up @@ -78,6 +79,9 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
private static final ParameterizedTypeReference<Map<String, String>> STRING_STRING_MAP = new ParameterizedTypeReference<Map<String, String>>() {
};

private Converter<OAuth2UserRequest, Converter<Map<String, Object>, Map<String, Object>>> attributesConverter = (
request) -> (attributes) -> attributes;

private WebClient webClient = WebClient.create();

@Override
Expand Down Expand Up @@ -123,7 +127,8 @@ public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2Aut
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
})
)
.bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP);
.bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP)
.mapNotNull((attributes) -> this.attributesConverter.convert(userRequest).convert(attributes));
return userAttributes.map((attrs) -> {
GrantedAuthority authority = new OAuth2UserAuthority(attrs);
Set<GrantedAuthority> authorities = new HashSet<>();
Expand Down Expand Up @@ -184,6 +189,32 @@ private WebClient.RequestHeadersSpec<?> getRequestHeaderSpec(OAuth2UserRequest u
// @formatter:on
}

/**
* Use this strategy to adapt user attributes into a format understood by Spring
* Security; by default, the original attributes are preserved.
*
* <p>
* This can be helpful, for example, if the user attribute is nested. Since Spring
* Security needs the username attribute to be at the top level, you can use this
* method to do:
*
* <pre>
* DefaultReactiveOAuth2UserService userService = new DefaultReactiveOAuth2UserService();
* userService.setAttributesConverter((userRequest) -> (attributes) ->
* Map&lt;String, Object&gt; userObject = (Map&lt;String, Object&gt;) attributes.get("user");
* attributes.put("user-name", userObject.get("user-name"));
* return attributes;
* });
* </pre>
* @param attributesConverter the attribute adaptation strategy to use
* @since 6.3
*/
public void setAttributesConverter(
Converter<OAuth2UserRequest, Converter<Map<String, Object>, Map<String, Object>>> attributesConverter) {
Assert.notNull(attributesConverter, "attributesConverter cannot be null");
this.attributesConverter = attributesConverter;
}

/**
* Sets the {@link WebClient} used for retrieving the user endpoint
* @param webClient the client to use
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,6 +16,7 @@

package org.springframework.security.oauth2.client.oidc.userinfo;

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
Expand All @@ -24,6 +25,8 @@
import java.util.Map;
import java.util.function.Function;

import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -32,13 +35,17 @@
import reactor.core.publisher.Mono;

import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.userinfo.DefaultReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
Expand Down Expand Up @@ -203,8 +210,62 @@ public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() {
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}

@Test
public void loadUserWhenNestedUserInfoSuccessThenReturnUser() throws IOException {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user\": {\"user-name\": \"user1\"},\n"
+ " \"sub\" : \"" + this.idToken.getSubject() + "\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
try (MockWebServer server = new MockWebServer()) {
server.start();
enqueueApplicationJsonBody(server, userInfoResponse);
String userInfoUri = server.url("/user").toString();
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.userNameAttributeName("user-name")
.build();
OidcReactiveOAuth2UserService userService = new OidcReactiveOAuth2UserService();
DefaultReactiveOAuth2UserService oAuth2UserService = new DefaultReactiveOAuth2UserService();
oAuth2UserService.setAttributesConverter((request) -> (attributes) -> {
Map<String, Object> user = (Map<String, Object>) attributes.get("user");
attributes.put("user-name", user.get("user-name"));
return attributes;
});
userService.setOauth2UserService(oAuth2UserService);
OAuth2User user = userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken))
.block();
assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes()).hasSize(13);
assertThat(((Map<?, ?>) user.getAttribute("user")).get("user-name")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
assertThat(user.getAuthorities()).hasSize(2);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OIDC_USER");
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
}

private OidcUserRequest userRequest() {
return new OidcUserRequest(this.registration.build(), this.accessToken, this.idToken);
}

private void enqueueApplicationJsonBody(MockWebServer server, String json) {
server.enqueue(
new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,12 @@ public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2
+ "from '" + userInfoUri + "': response contains invalid content type 'text/plain'.");
}

@Test
public void setAttributesConverterWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.userService.setAttributesConverter(null));
}

private DefaultOAuth2UserService withMockResponse(Map<String, Object> response) {
ResponseEntity<Map<String, Object>> responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = mock(Converter.class);
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 Down Expand Up @@ -165,6 +165,46 @@ public void loadUserWhenUserInfo201CreatedResponseThenReturnUser() {
assertThatNoException().isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block());
}

@Test
public void loadUserWhenNestedUserInfoSuccessThenReturnUser() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user\": {\"user-name\": \"user1\"},\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistration.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.userNameAttributeName("user-name")
.build();
DefaultReactiveOAuth2UserService userService = new DefaultReactiveOAuth2UserService();
userService.setAttributesConverter((request) -> (attributes) -> {
Map<String, Object> user = (Map<String, Object>) attributes.get("user");
attributes.put("user-name", user.get("user-name"));
return attributes;
});
OAuth2User user = userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)).block();
assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes()).hasSize(7);
assertThat(((Map<?, ?>) user.getAttribute("user")).get("user-name")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER");
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}

// gh-5500
@Test
public void loadUserWhenAuthenticationMethodHeaderSuccessResponseThenHttpMethodGet() throws Exception {
Expand Down Expand Up @@ -290,6 +330,12 @@ public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2
+ "response contains invalid content type 'text/plain'");
}

@Test
public void setAttributesConverterWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.userService.setAttributesConverter(null));
}

private DefaultReactiveOAuth2UserService withMockResponse(Map<String, Object> body) {
WebClient real = WebClient.builder().build();
WebClient.RequestHeadersUriSpec spec = spy(real.post());
Expand Down

0 comments on commit e3b5da6

Please sign in to comment.