Răsfoiți Sursa

Add support for nested username attribute in DefaultOAuth2User

Closes gh-14186

Signed-off-by: ahmd-nabil <ahm3dnabil99@gmail.com>
ahmd-nabil 1 an în urmă
părinte
comite
d9d22c75a2

+ 31 - 2
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserService.java

@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2020 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.
@@ -76,6 +76,9 @@ public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserReq
 
 	private Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter();
 
+	private Converter<OAuth2UserRequest, Converter<Map<String, Object>, Map<String, Object>>> attributesConverter = (
+			request) -> (attributes) -> attributes;
+
 	private RestOperations restOperations;
 
 	public DefaultOAuth2UserService() {
@@ -108,7 +111,7 @@ public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserReq
 		}
 		RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
 		ResponseEntity<Map<String, Object>> response = getResponse(userRequest, request);
-		Map<String, Object> userAttributes = response.getBody();
+		Map<String, Object> userAttributes = this.attributesConverter.convert(userRequest).convert(response.getBody());
 		Set<GrantedAuthority> authorities = new LinkedHashSet<>();
 		authorities.add(new OAuth2UserAuthority(userAttributes));
 		OAuth2AccessToken token = userRequest.getAccessToken();
@@ -118,6 +121,32 @@ public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserReq
 		return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
 	}
 
+	/**
+	 * 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>
+	 *     DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
+	 *     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;
+	}
+
 	private ResponseEntity<Map<String, Object>> getResponse(OAuth2UserRequest userRequest, RequestEntity<?> request) {
 		try {
 			return this.restOperations.exchange(request, PARAMETERIZED_RESPONSE_TYPE);

+ 46 - 1
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java

@@ -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.
@@ -52,6 +52,8 @@ import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
 import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
 import org.springframework.security.oauth2.core.oidc.user.OidcUser;
 import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
+import org.springframework.security.oauth2.core.user.OAuth2User;
+import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -492,6 +494,49 @@ public class OidcUserServiceTests {
 		assertThat(user.getUserInfo()).isNotNull();
 	}
 
+	@Test
+	public void loadUserWhenNestedUserInfoSuccessThenReturnUser() {
+		// @formatter:off
+		String userInfoResponse = "{\n"
+				+ "   \"user\": {\"user-name\": \"user1\"},\n"
+				+ "   \"sub\" : \"subject1\",\n"
+				+ "   \"first-name\": \"first\",\n"
+				+ "   \"last-name\": \"last\",\n"
+				+ "   \"middle-name\": \"middle\",\n"
+				+ "   \"address\": \"address\",\n"
+				+ "   \"email\": \"user1@example.com\"\n"
+				+ "}\n";
+		// @formatter:on
+		this.server.enqueue(jsonResponse(userInfoResponse));
+		String userInfoUri = this.server.url("/user").toString();
+		ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
+			.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
+			.userNameAttributeName("user-name")
+			.build();
+		OidcUserService userService = new OidcUserService();
+		DefaultOAuth2UserService oAuth2UserService = new DefaultOAuth2UserService();
+		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));
+		assertThat(user.getName()).isEqualTo("user1");
+		assertThat(user.getAttributes()).hasSize(9);
+		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(3);
+		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 MockResponse jsonResponse(String json) {
 		// @formatter:off
 		return new MockResponse()

+ 41 - 1
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java

@@ -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.
@@ -158,6 +158,46 @@ public class DefaultOAuth2UserServiceTests {
 		assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
 	}
 
+	@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
+		this.server.enqueue(jsonResponse(userInfoResponse));
+		String userInfoUri = this.server.url("/user").toString();
+		ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
+			.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
+			.userNameAttributeName("user-name")
+			.build();
+		DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
+		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));
+		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());
+	}
+
 	@Test
 	public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
 		// @formatter:off