Skip to content

Add support for nested user-name-attribute using dot notation #16857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 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 @@ -17,6 +17,7 @@
package org.springframework.security.oauth2.client.userinfo;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;

Expand Down Expand Up @@ -95,6 +96,16 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
ResponseEntity<Map<String, Object>> response = getResponse(userRequest, request);
OAuth2AccessToken token = userRequest.getAccessToken();
Map<String, Object> attributes = this.attributesConverter.convert(userRequest).convert(response.getBody());

if (userNameAttributeName.contains(".") && !attributes.containsKey(userNameAttributeName)) {
Object nestedValue = extractNestedAttribute(attributes, userNameAttributeName);
if (nestedValue != null) {
Map<String, Object> enhancedAttributes = new HashMap<>(attributes);
enhancedAttributes.put(userNameAttributeName, nestedValue);
attributes = enhancedAttributes;
}
}

Collection<GrantedAuthority> authorities = getAuthorities(token, attributes, userNameAttributeName);
return new DefaultOAuth2User(authorities, attributes, userNameAttributeName);
}
Expand Down Expand Up @@ -197,6 +208,42 @@ private Collection<GrantedAuthority> getAuthorities(OAuth2AccessToken token, Map
return authorities;
}

/**
* Extract a value from nested attributes using a dot-notation path. For example,
* "data.username" would extract the "username" field from the "data" object.
* @param attributes the map of attributes
* @param attributePath the attribute path in dot notation
* @return the value at the specified path, or null if not found
*/
private Object extractNestedAttribute(Map<String, Object> attributes, String attributePath) {
if (attributes == null || attributePath == null) {
return null;
}

if (!attributePath.contains(".")) {
return attributes.get(attributePath);
}

String[] pathParts = attributePath.split("\\.");
Object currentValue = attributes;

for (String part : pathParts) {
if (!(currentValue instanceof Map)) {
return null;
}

@SuppressWarnings("unchecked")
Map<String, Object> currentMap = (Map<String, Object>) currentValue;
currentValue = currentMap.get(part);

if (currentValue == null) {
return null;
}
}

return currentValue;
}

/**
* Sets the {@link Converter} used for converting the {@link OAuth2UserRequest} to a
* {@link RequestEntity} representation of the UserInfo Request.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 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.userinfo;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -128,7 +129,19 @@ public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2Aut
})
)
.bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP)
.mapNotNull((attributes) -> this.attributesConverter.convert(userRequest).convert(attributes));
.mapNotNull((attributes) -> {
Map<String, Object> convertedAttributes = this.attributesConverter.convert(userRequest).convert(attributes);
if (userNameAttributeName.contains(".") && !convertedAttributes.containsKey(userNameAttributeName)) {
Object nestedValue = extractNestedAttribute(convertedAttributes, userNameAttributeName);
if (nestedValue != null) {
Map<String, Object> enhancedAttributes = new HashMap<>(convertedAttributes);
enhancedAttributes.put(userNameAttributeName, nestedValue);
return enhancedAttributes;
}
}

return convertedAttributes;
});
return userAttributes.map((attrs) -> {
GrantedAuthority authority = new OAuth2UserAuthority(attrs, userNameAttributeName);
Set<GrantedAuthority> authorities = new HashSet<>();
Expand Down Expand Up @@ -189,6 +202,42 @@ private WebClient.RequestHeadersSpec<?> getRequestHeaderSpec(OAuth2UserRequest u
// @formatter:on
}

/**
* Extract a value from nested attributes using a dot-notation path. For example,
* "data.username" would extract the "username" field from the "data" object.
* @param attributes the map of attributes
* @param attributePath the attribute path in dot notation
* @return the value at the specified path, or null if not found
*/
private Object extractNestedAttribute(Map<String, Object> attributes, String attributePath) {
if (attributes == null || attributePath == null) {
return null;
}

if (!attributePath.contains(".")) {
return attributes.get(attributePath);
}

String[] pathParts = attributePath.split("\\.");
Object currentValue = attributes;

for (String part : pathParts) {
if (!(currentValue instanceof Map)) {
return null;
}

@SuppressWarnings("unchecked")
Map<String, Object> currentMap = (Map<String, Object>) currentValue;
currentValue = currentMap.get(part);

if (currentValue == null) {
return null;
}
}

return currentValue;
}

/**
* Use this strategy to adapt user attributes into a format understood by Spring
* Security; by default, the original attributes are preserved.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 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 @@ -200,6 +200,63 @@ public void loadUserWhenNestedUserInfoSuccessThenReturnUser() {
assertThat(userAuthority.getUserNameAttributeName()).isEqualTo("user-name");
}

@Test
public void loadUserWhenUserNameAttributeIsNestedThenExtractCorrectly() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"data\": {\n"
+ " \"id\": \"2244994945\",\n"
+ " \"username\": \"testuser\",\n"
+ " \"name\": \"Test User\"\n"
+ " },\n"
+ " \"meta\": {\n"
+ " \"version\": \"1.0\"\n"
+ " }\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("data.username")
.build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(user.getName()).isEqualTo("testuser");
assertThat(user.getAttributes()).containsKey("data");
Map<String, Object> data = (Map<String, Object>) user.getAttributes().get("data");
assertThat(data).containsEntry("username", "testuser");
assertThat(user.getAttributes()).containsKey("data.username");
assertThat(user.getAttributes().get("data.username")).isEqualTo("testuser");
}

@Test
public void loadUserWhenUserNameAttributeIsMultiLevelNestedThenExtractCorrectly() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"response\": {\n"
+ " \"user\": {\n"
+ " \"profile\": {\n"
+ " \"id\": \"12345\",\n"
+ " \"login\": \"deepnested\",\n"
+ " \"email\": \"[email protected]\"\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " \"status\": \"success\"\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("response.user.profile.login")
.build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(user.getName()).isEqualTo("deepnested");
assertThat(user.getAttributes()).containsKey("response.user.profile.login");
assertThat(user.getAttributes().get("response.user.profile.login")).isEqualTo("deepnested");
}

@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
// @formatter:off
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 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 @@ -207,6 +207,65 @@ public void loadUserWhenNestedUserInfoSuccessThenReturnUser() {
assertThat(userAuthority.getUserNameAttributeName()).isEqualTo("user-name");
}

@Test
public void loadUserWhenUserNameAttributeIsNestedThenExtractCorrectly() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"data\": {\n"
+ " \"id\": \"2244994945\",\n"
+ " \"username\": \"testuser\",\n"
+ " \"name\": \"Test User\"\n"
+ " },\n"
+ " \"meta\": {\n"
+ " \"version\": \"1.0\"\n"
+ " }\n"
+ "}\n";
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistration.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.userNameAttributeName("data.username")
.build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken))
.block();
assertThat(user.getName()).isEqualTo("testuser");
assertThat(user.getAttributes()).containsKey("data");
Map<String, Object> data = (Map<String, Object>) user.getAttributes().get("data");
assertThat(data).containsEntry("username", "testuser");
assertThat(user.getAttributes()).containsKey("data.username");
assertThat(user.getAttributes().get("data.username")).isEqualTo("testuser");
}

@Test
public void loadUserWhenUserNameAttributeIsMultiLevelNestedThenExtractCorrectly() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"response\": {\n"
+ " \"user\": {\n"
+ " \"profile\": {\n"
+ " \"id\": \"12345\",\n"
+ " \"login\": \"deepnested\",\n"
+ " \"email\": \"[email protected]\"\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " \"status\": \"success\"\n"
+ "}\n";
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistration.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.userNameAttributeName("response.user.profile.login")
.build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken))
.block();
assertThat(user.getName()).isEqualTo("deepnested");
assertThat(user.getAttributes()).containsKey("response.user.profile.login");
assertThat(user.getAttributes().get("response.user.profile.login")).isEqualTo("deepnested");
}

// gh-5500
@Test
public void loadUserWhenAuthenticationMethodHeaderSuccessResponseThenHttpMethodGet() throws Exception {
Expand Down