Skip to content

Commit 9667229

Browse files
idosaljgrandja
authored andcommitted
Initial implementation of User Info Endpoint
Issue gh-176
1 parent 33bac0f commit 9667229

File tree

4 files changed

+332
-0
lines changed

4 files changed

+332
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
/*
2+
* Copyright 2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.security.oauth2.core.oidc.http.converter;
17+
18+
import org.springframework.core.ParameterizedTypeReference;
19+
import org.springframework.core.convert.TypeDescriptor;
20+
import org.springframework.core.convert.converter.Converter;
21+
import org.springframework.http.HttpInputMessage;
22+
import org.springframework.http.HttpOutputMessage;
23+
import org.springframework.http.MediaType;
24+
import org.springframework.http.converter.HttpMessageConverter;
25+
import org.springframework.http.converter.GenericHttpMessageConverter;
26+
import org.springframework.http.converter.HttpMessageNotWritableException;
27+
import org.springframework.http.converter.HttpMessageNotReadableException;
28+
import org.springframework.http.converter.AbstractHttpMessageConverter;
29+
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
30+
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
31+
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
32+
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
33+
import org.springframework.util.Assert;
34+
35+
import java.util.HashMap;
36+
import java.util.Map;
37+
38+
/**
39+
* A {@link HttpMessageConverter} for an {@link OidcUserInfo OIDC User Info Response}.
40+
*
41+
* @author Ido Salomon
42+
* @see AbstractHttpMessageConverter
43+
* @see OidcUserInfo
44+
* @since 0.1.1
45+
*/
46+
public class OidcUserInfoHttpMessageConverter extends AbstractHttpMessageConverter<OidcUserInfo> {
47+
48+
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP =
49+
new ParameterizedTypeReference<Map<String, Object>>() {
50+
};
51+
52+
private final GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters.getJsonMessageConverter();
53+
54+
private Converter<Map<String, Object>, OidcUserInfo> oidcUserInfoConverter = new OidcUserInfoConverter();
55+
private Converter<OidcUserInfo, Map<String, Object>> oidcUserInfoParametersConverter = OidcUserInfo::getClaims;
56+
57+
public OidcUserInfoHttpMessageConverter() {
58+
super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
59+
}
60+
61+
@Override
62+
protected boolean supports(Class<?> clazz) {
63+
return OidcUserInfo.class.isAssignableFrom(clazz);
64+
}
65+
66+
@Override
67+
@SuppressWarnings("unchecked")
68+
protected OidcUserInfo readInternal(Class<? extends OidcUserInfo> clazz, HttpInputMessage inputMessage)
69+
throws HttpMessageNotReadableException {
70+
try {
71+
Map<String, Object> oidcUserInfoParameters =
72+
(Map<String, Object>) this.jsonMessageConverter.read(STRING_OBJECT_MAP.getType(), null, inputMessage);
73+
return this.oidcUserInfoConverter.convert(oidcUserInfoParameters);
74+
} catch (Exception ex) {
75+
throw new HttpMessageNotReadableException(
76+
"An error occurred reading the OIDC User Info: " + ex.getMessage(), ex, inputMessage);
77+
}
78+
}
79+
80+
@Override
81+
protected void writeInternal(OidcUserInfo oidcUserInfo, HttpOutputMessage outputMessage)
82+
throws HttpMessageNotWritableException {
83+
try {
84+
Map<String, Object> oidcUserInfoResponseParameters =
85+
this.oidcUserInfoParametersConverter.convert(oidcUserInfo);
86+
this.jsonMessageConverter.write(
87+
oidcUserInfoResponseParameters,
88+
STRING_OBJECT_MAP.getType(),
89+
MediaType.APPLICATION_JSON,
90+
outputMessage
91+
);
92+
} catch (Exception ex) {
93+
throw new HttpMessageNotWritableException(
94+
"An error occurred writing the OIDC User Info response: " + ex.getMessage(), ex);
95+
}
96+
}
97+
98+
/**
99+
* Sets the {@link Converter} used for converting the OIDC User Info parameters
100+
* to an {@link OidcUserInfo}.
101+
*
102+
* @param oidcUserInfoConverter the {@link Converter} used for converting to an
103+
* {@link OidcUserInfo}
104+
*/
105+
public final void setOidcUserInfoConverter(Converter<Map<String, Object>, OidcUserInfo> oidcUserInfoConverter) {
106+
Assert.notNull(oidcUserInfoConverter, "oidcUserInfoConverter cannot be null");
107+
this.oidcUserInfoConverter = oidcUserInfoConverter;
108+
}
109+
110+
/**
111+
* Sets the {@link Converter} used for converting the {@link OidcUserInfo} to a
112+
* {@code Map} representation of the OIDC User Info.
113+
*
114+
* @param oidcUserInfoParametersConverter the {@link Converter} used for converting to a
115+
* {@code Map} representation of the OIDC User Info
116+
*/
117+
public final void setOidcUserInfoParametersConverter(
118+
Converter<OidcUserInfo, Map<String, Object>> oidcUserInfoParametersConverter) {
119+
Assert.notNull(oidcUserInfoParametersConverter, "oidcUserInfoParametersConverter cannot be null");
120+
this.oidcUserInfoParametersConverter = oidcUserInfoParametersConverter;
121+
}
122+
123+
private static final class OidcUserInfoConverter implements Converter<Map<String, Object>, OidcUserInfo> {
124+
private static final ClaimConversionService CLAIM_CONVERSION_SERVICE = ClaimConversionService.getSharedInstance();
125+
private static final TypeDescriptor OBJECT_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Object.class);
126+
private static final TypeDescriptor BOOLEAN_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Boolean.class);
127+
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
128+
private final ClaimTypeConverter claimTypeConverter;
129+
130+
private OidcUserInfoConverter() {
131+
Converter<Object, ?> stringConverter = getConverter(STRING_TYPE_DESCRIPTOR);
132+
Converter<Object, ?> booleanConverter = getConverter(BOOLEAN_TYPE_DESCRIPTOR);
133+
134+
Map<String, Converter<Object, ?>> claimConverters = new HashMap<>();
135+
claimConverters.put(StandardClaimNames.SUB, stringConverter);
136+
claimConverters.put(StandardClaimNames.PROFILE, stringConverter);
137+
claimConverters.put(StandardClaimNames.ADDRESS, stringConverter);
138+
claimConverters.put(StandardClaimNames.BIRTHDATE, stringConverter);
139+
claimConverters.put(StandardClaimNames.EMAIL, stringConverter);
140+
claimConverters.put(StandardClaimNames.EMAIL_VERIFIED, booleanConverter);
141+
claimConverters.put(StandardClaimNames.NAME, stringConverter);
142+
claimConverters.put(StandardClaimNames.GIVEN_NAME, stringConverter);
143+
claimConverters.put(StandardClaimNames.MIDDLE_NAME, stringConverter);
144+
claimConverters.put(StandardClaimNames.FAMILY_NAME, stringConverter);
145+
claimConverters.put(StandardClaimNames.NICKNAME, stringConverter);
146+
claimConverters.put(StandardClaimNames.PREFERRED_USERNAME, stringConverter);
147+
claimConverters.put(StandardClaimNames.LOCALE, stringConverter);
148+
claimConverters.put(StandardClaimNames.GENDER, stringConverter);
149+
claimConverters.put(StandardClaimNames.PHONE_NUMBER, stringConverter);
150+
claimConverters.put(StandardClaimNames.PHONE_NUMBER_VERIFIED, stringConverter);
151+
claimConverters.put(StandardClaimNames.PICTURE, stringConverter);
152+
claimConverters.put(StandardClaimNames.ZONEINFO, stringConverter);
153+
claimConverters.put(StandardClaimNames.WEBSITE, stringConverter);
154+
claimConverters.put(StandardClaimNames.UPDATED_AT, stringConverter);
155+
156+
this.claimTypeConverter = new ClaimTypeConverter(claimConverters);
157+
}
158+
159+
@Override
160+
public OidcUserInfo convert(Map<String, Object> source) {
161+
Map<String, Object> parsedClaims = this.claimTypeConverter.convert(source);
162+
return new OidcUserInfo(parsedClaims);
163+
}
164+
165+
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
166+
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
167+
}
168+
}
169+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package org.springframework.security.oauth2.server.authorization.oidc;
2+
3+
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
4+
5+
public class DefaultUserInfoClaimsMapper implements UserInfoClaimsMapper {
6+
7+
public OidcUserInfo map(Object principal) {
8+
return null; // TODO
9+
}
10+
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package org.springframework.security.oauth2.server.authorization.oidc;
2+
3+
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
4+
5+
public interface UserInfoClaimsMapper {
6+
7+
OidcUserInfo map(Object principal);
8+
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/*
2+
* Copyright 2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.security.oauth2.server.authorization.oidc.web;
17+
18+
import java.io.IOException;
19+
import java.util.Arrays;
20+
import java.util.HashSet;
21+
import java.util.Map;
22+
import java.util.Set;
23+
import java.util.stream.Collectors;
24+
25+
import javax.servlet.FilterChain;
26+
import javax.servlet.ServletException;
27+
import javax.servlet.http.HttpServletRequest;
28+
import javax.servlet.http.HttpServletResponse;
29+
30+
import org.springframework.http.HttpMethod;
31+
import org.springframework.http.MediaType;
32+
import org.springframework.http.server.ServletServerHttpResponse;
33+
import org.springframework.security.core.Authentication;
34+
import org.springframework.security.core.context.SecurityContextHolder;
35+
import org.springframework.security.oauth2.core.OAuth2AccessToken;
36+
import org.springframework.security.oauth2.core.oidc.OidcScopes;
37+
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
38+
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
39+
import org.springframework.security.oauth2.core.oidc.http.converter.OidcUserInfoHttpMessageConverter;
40+
import org.springframework.security.oauth2.server.authorization.oidc.UserInfoClaimsMapper;
41+
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
42+
import org.springframework.security.web.util.matcher.OrRequestMatcher;
43+
import org.springframework.security.web.util.matcher.RequestMatcher;
44+
import org.springframework.web.filter.OncePerRequestFilter;
45+
46+
/**
47+
* A {@code Filter} that processes OpenID User Info requests.
48+
*
49+
* @author Ido Salomon
50+
* @see OidcUserInfo
51+
* @see <a target="_blank" href="https://openid.net/specs/openid-connect-core-1_0.html#UserInfoRequest">5.3.1. UserInfo Request</a>
52+
* @since 0.1.1
53+
*/
54+
public class OidcUserInfoEndpointFilter extends OncePerRequestFilter {
55+
56+
/**
57+
* The default endpoint {@code URI} for OpenID User Info requests.
58+
*/
59+
public static final String DEFAULT_OIDC_USER_INFO_ENDPOINT_URI = "/userinfo";
60+
61+
private final RequestMatcher requestMatcher;
62+
private final OidcUserInfoHttpMessageConverter oidcUserInfoHttpMessageConverter =
63+
new OidcUserInfoHttpMessageConverter();
64+
private final UserInfoClaimsMapper userInfoClaimsMapper;
65+
66+
public OidcUserInfoEndpointFilter(UserInfoClaimsMapper userInfoClaimsMapper) {
67+
AntPathRequestMatcher userInfoGetMatcher = new AntPathRequestMatcher(
68+
DEFAULT_OIDC_USER_INFO_ENDPOINT_URI,
69+
HttpMethod.GET.name()
70+
);
71+
AntPathRequestMatcher userInfoPostMatcher = new AntPathRequestMatcher(
72+
DEFAULT_OIDC_USER_INFO_ENDPOINT_URI,
73+
HttpMethod.POST.name()
74+
);
75+
this.requestMatcher = new OrRequestMatcher(userInfoGetMatcher, userInfoPostMatcher);
76+
this.userInfoClaimsMapper = userInfoClaimsMapper;
77+
}
78+
79+
@Override
80+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
81+
throws ServletException, IOException {
82+
83+
if (!this.requestMatcher.matches(request)) {
84+
filterChain.doFilter(request, response);
85+
return;
86+
}
87+
88+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
89+
Object authenticationDetails = authentication.getDetails();
90+
Object principal = authentication.getPrincipal();
91+
OidcUserInfo oidcUserInfo = userInfoClaimsMapper.map(principal);
92+
93+
if (authenticationDetails instanceof OAuth2AccessToken) {
94+
oidcUserInfo = getUserInfoClaimsRequestedByScope(oidcUserInfo, ((OAuth2AccessToken) authenticationDetails).getScopes());
95+
} else {
96+
oidcUserInfo = OidcUserInfo.builder()
97+
.subject(oidcUserInfo.getSubject())
98+
.build();
99+
}
100+
101+
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
102+
this.oidcUserInfoHttpMessageConverter.write(
103+
oidcUserInfo, MediaType.APPLICATION_JSON, httpResponse);
104+
}
105+
106+
private OidcUserInfo getUserInfoClaimsRequestedByScope(OidcUserInfo userInfo, Set<String> scopes) {
107+
Set<String> scopeRequestedClaimNames = getScopeRequestedClaimNames(scopes);
108+
109+
Map<String, Object> scopeRequestedClaims = userInfo.getClaims().entrySet().stream()
110+
.filter(claim -> scopeRequestedClaimNames.contains(claim.getKey()))
111+
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
112+
113+
return new OidcUserInfo(scopeRequestedClaims);
114+
}
115+
116+
private Set<String> getScopeRequestedClaimNames(Set<String> scopes) {
117+
Set<String> scopeRequestedClaimNames = new HashSet<>(Arrays.asList(StandardClaimNames.SUB));
118+
Set<String> profileClaimNames = new HashSet<>(Arrays.asList(StandardClaimNames.NAME,
119+
StandardClaimNames.FAMILY_NAME, StandardClaimNames.GIVEN_NAME, StandardClaimNames.MIDDLE_NAME,
120+
StandardClaimNames.NICKNAME, StandardClaimNames.PREFERRED_USERNAME, StandardClaimNames.PROFILE,
121+
StandardClaimNames.PICTURE, StandardClaimNames.WEBSITE, StandardClaimNames.GENDER,
122+
StandardClaimNames.BIRTHDATE, StandardClaimNames.ZONEINFO, StandardClaimNames.LOCALE, StandardClaimNames.UPDATED_AT));
123+
Set<String> emailClaimNames = new HashSet<>(Arrays.asList(StandardClaimNames.EMAIL, StandardClaimNames.EMAIL_VERIFIED));
124+
String addressClaimName = StandardClaimNames.ADDRESS;
125+
Set<String> phoneClaimNames = new HashSet<>(Arrays.asList(StandardClaimNames.PHONE_NUMBER, StandardClaimNames.PHONE_NUMBER_VERIFIED));
126+
127+
if (scopes.contains(OidcScopes.ADDRESS)) {
128+
scopeRequestedClaimNames.add(addressClaimName);
129+
}
130+
if (scopes.contains(OidcScopes.EMAIL)) {
131+
scopeRequestedClaimNames.addAll(emailClaimNames);
132+
}
133+
if (scopes.contains(OidcScopes.PHONE)) {
134+
scopeRequestedClaimNames.addAll(phoneClaimNames);
135+
}
136+
if (scopes.contains(OidcScopes.PROFILE)) {
137+
scopeRequestedClaimNames.addAll(profileClaimNames);
138+
}
139+
140+
return scopeRequestedClaimNames;
141+
}
142+
143+
}

0 commit comments

Comments
 (0)