Skip to content

Commit 037e6fb

Browse files
committed
Ensure ID Token is updated after refresh token (Reactive)
Closes gh-17188 Signed-off-by: Evgeniy Cheban <mister.cheban@gmail.com>
1 parent 20493ef commit 037e6fb

7 files changed

Lines changed: 873 additions & 8 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,312 @@
1+
/*
2+
* Copyright 2004-present 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+
17+
package org.springframework.security.oauth2.client;
18+
19+
import java.time.Duration;
20+
import java.util.Collection;
21+
import java.util.HashSet;
22+
import java.util.List;
23+
import java.util.Map;
24+
import java.util.Set;
25+
26+
import reactor.core.publisher.Mono;
27+
28+
import org.springframework.security.core.Authentication;
29+
import org.springframework.security.core.GrantedAuthority;
30+
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
31+
import org.springframework.security.core.context.SecurityContext;
32+
import org.springframework.security.core.context.SecurityContextImpl;
33+
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
34+
import org.springframework.security.oauth2.client.oidc.authentication.ReactiveOidcIdTokenDecoderFactory;
35+
import org.springframework.security.oauth2.client.oidc.userinfo.OidcReactiveOAuth2UserService;
36+
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
37+
import org.springframework.security.oauth2.client.registration.ClientRegistration;
38+
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
39+
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
40+
import org.springframework.security.oauth2.core.OAuth2Error;
41+
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
42+
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
43+
import org.springframework.security.oauth2.core.oidc.OidcScopes;
44+
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
45+
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
46+
import org.springframework.security.oauth2.jwt.JwtException;
47+
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
48+
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory;
49+
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
50+
import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository;
51+
import org.springframework.util.Assert;
52+
import org.springframework.util.StringUtils;
53+
import org.springframework.web.server.ServerWebExchange;
54+
55+
/**
56+
* A {@link ReactiveOAuth2AuthorizationSuccessHandler} that refreshes an {@link OidcUser}
57+
* in the {@link SecurityContext} if the refreshed {@link OidcIdToken} is valid according
58+
* to <a href=
59+
* "https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse">OpenID
60+
* Connect Core 1.0 - Section 12.2 Successful Refresh Response</a>
61+
*
62+
* @author Evgeniy Cheban
63+
* @since 7.1
64+
*/
65+
public final class RefreshTokenReactiveOAuth2AuthorizationSuccessHandler
66+
implements ReactiveOAuth2AuthorizationSuccessHandler {
67+
68+
private static final String INVALID_ID_TOKEN_ERROR_CODE = "invalid_id_token";
69+
70+
private static final String INVALID_NONCE_ERROR_CODE = "invalid_nonce";
71+
72+
private static final String REFRESH_TOKEN_RESPONSE_ERROR_URI = "https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse";
73+
74+
// @formatter:off
75+
private static final Mono<ServerWebExchange> currentServerWebExchangeMono = Mono.deferContextual(Mono::just)
76+
.filter((c) -> c.hasKey(ServerWebExchange.class))
77+
.map((c) -> c.get(ServerWebExchange.class));
78+
// @formatter:on
79+
80+
private ServerSecurityContextRepository serverSecurityContextRepository = new WebSessionServerSecurityContextRepository();
81+
82+
private ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = new ReactiveOidcIdTokenDecoderFactory();
83+
84+
private ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService = new OidcReactiveOAuth2UserService();
85+
86+
private GrantedAuthoritiesMapper authoritiesMapper = (authorities) -> authorities;
87+
88+
private Duration clockSkew = Duration.ofSeconds(60);
89+
90+
/**
91+
* Sets a {@link ServerSecurityContextRepository} to use for refreshing a
92+
* {@link SecurityContext}, defaults to
93+
* {@link WebSessionServerSecurityContextRepository}.
94+
* @param serverSecurityContextRepository the {@link ServerSecurityContextRepository}
95+
* to use
96+
*/
97+
public void setServerSecurityContextRepository(ServerSecurityContextRepository serverSecurityContextRepository) {
98+
Assert.notNull(serverSecurityContextRepository, "serverSecurityContextRepository cannot be null");
99+
this.serverSecurityContextRepository = serverSecurityContextRepository;
100+
}
101+
102+
/**
103+
* Sets a {@link ReactiveJwtDecoderFactory} to use for decoding refreshed oidc
104+
* id-token, defaults to {@link ReactiveOidcIdTokenDecoderFactory}.
105+
* @param jwtDecoderFactory the {@link ReactiveJwtDecoderFactory} to use
106+
*/
107+
public void setJwtDecoderFactory(ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory) {
108+
Assert.notNull(jwtDecoderFactory, "jwtDecoderFactory cannot be null");
109+
this.jwtDecoderFactory = jwtDecoderFactory;
110+
}
111+
112+
/**
113+
* Sets a {@link GrantedAuthoritiesMapper} to use for mapping
114+
* {@link GrantedAuthority}s, defaults to no-op implementation.
115+
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} to use
116+
*/
117+
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
118+
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
119+
this.authoritiesMapper = authoritiesMapper;
120+
}
121+
122+
/**
123+
* Sets a {@link ReactiveOAuth2UserService} to use for loading an {@link OidcUser}
124+
* from refreshed oidc id-token, defaults to {@link OidcReactiveOAuth2UserService}.
125+
* @param userService the {@link ReactiveOAuth2UserService} to use
126+
*/
127+
public void setUserService(ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService) {
128+
Assert.notNull(userService, "userService cannot be null");
129+
this.userService = userService;
130+
}
131+
132+
/**
133+
* Sets the maximum acceptable clock skew, which is used when checking the
134+
* {@link OidcIdToken#getIssuedAt()} to match the existing
135+
* {@link OidcUser#getIdToken()}'s issuedAt time, defaults to 60 seconds.
136+
* @param clockSkew the maximum acceptable clock skew to use
137+
*/
138+
public void setClockSkew(Duration clockSkew) {
139+
Assert.notNull(clockSkew, "clockSkew cannot be null");
140+
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
141+
this.clockSkew = clockSkew;
142+
}
143+
144+
@Override
145+
public Mono<Void> onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal,
146+
Map<String, Object> attributes) {
147+
if (!(principal instanceof OAuth2AuthenticationToken authenticationToken)
148+
|| authenticationToken.getClass() != OAuth2AuthenticationToken.class) {
149+
// If the application customizes the authentication result, then a custom
150+
// handler should be provided.
151+
return Mono.empty();
152+
}
153+
// The current principal must be an OidcUser.
154+
if (!(authenticationToken.getPrincipal() instanceof OidcUser existingOidcUser)) {
155+
return Mono.empty();
156+
}
157+
ClientRegistration clientRegistration = authorizedClient.getClientRegistration();
158+
// The registrationId must match the one used to log in.
159+
if (!authenticationToken.getAuthorizedClientRegistrationId().equals(clientRegistration.getRegistrationId())) {
160+
return Mono.empty();
161+
}
162+
// Create, validate OidcIdToken and refresh OidcUser in the SecurityContext.
163+
return Mono.zip(serverWebExchange(attributes), accessTokenResponse(attributes)).flatMap((t2) -> {
164+
ReactiveJwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
165+
Map<String, Object> additionalParameters = t2.getT2().getAdditionalParameters();
166+
return jwtDecoder.decode((String) additionalParameters.get(OidcParameterNames.ID_TOKEN))
167+
.onErrorMap(JwtException.class, (ex) -> {
168+
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, ex.getMessage(),
169+
null);
170+
return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), ex);
171+
})
172+
.map((jwt) -> new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(),
173+
jwt.getClaims()))
174+
.doOnNext((idToken) -> validateIdToken(existingOidcUser, idToken))
175+
.flatMap((idToken) -> {
176+
OidcUserRequest userRequest = new OidcUserRequest(clientRegistration,
177+
authorizedClient.getAccessToken(), idToken);
178+
return this.userService.loadUser(userRequest);
179+
})
180+
.flatMap((oidcUser) -> refreshSecurityContext(t2.getT1(), clientRegistration, authenticationToken,
181+
oidcUser));
182+
});
183+
}
184+
185+
private Mono<ServerWebExchange> serverWebExchange(Map<String, Object> attributes) {
186+
if (attributes.get(ServerWebExchange.class.getName()) instanceof ServerWebExchange exchange) {
187+
return Mono.just(exchange);
188+
}
189+
return currentServerWebExchangeMono;
190+
}
191+
192+
private Mono<OAuth2AccessTokenResponse> accessTokenResponse(Map<String, Object> attributes) {
193+
if (attributes.get(OAuth2AccessTokenResponse.class.getName()) instanceof OAuth2AccessTokenResponse response) {
194+
// The response must contain the openid scope.
195+
if (!response.getAccessToken().getScopes().contains(OidcScopes.OPENID)) {
196+
return Mono.empty();
197+
}
198+
// The response must contain an id_token.
199+
Map<String, Object> additionalParameters = response.getAdditionalParameters();
200+
if (!StringUtils.hasText((String) additionalParameters.get(OidcParameterNames.ID_TOKEN))) {
201+
return Mono.empty();
202+
}
203+
return Mono.just(response);
204+
}
205+
return Mono.empty();
206+
}
207+
208+
private void validateIdToken(OidcUser existingOidcUser, OidcIdToken idToken) {
209+
// OpenID Connect Core 1.0 - Section 12.2 Successful Refresh Response
210+
// If an ID Token is returned as a result of a token refresh request, the
211+
// following requirements apply:
212+
// its iss Claim Value MUST be the same as in the ID Token issued when the
213+
// original authentication occurred,
214+
validateIssuer(existingOidcUser, idToken);
215+
// its sub Claim Value MUST be the same as in the ID Token issued when the
216+
// original authentication occurred,
217+
validateSubject(existingOidcUser, idToken);
218+
// its iat Claim MUST represent the time that the new ID Token is issued,
219+
validateIssuedAt(existingOidcUser, idToken);
220+
// its aud Claim Value MUST be the same as in the ID Token issued when the
221+
// original authentication occurred,
222+
validateAudience(existingOidcUser, idToken);
223+
// if the ID Token contains an auth_time Claim, its value MUST represent the time
224+
// of the original authentication - not the time that the new ID token is issued,
225+
validateAuthenticatedAt(existingOidcUser, idToken);
226+
// it SHOULD NOT have a nonce Claim, even when the ID Token issued at the time of
227+
// the original authentication contained nonce; however, if it is present, its
228+
// value MUST be the same as in the ID Token issued at the time of the original
229+
// authentication,
230+
validateNonce(existingOidcUser, idToken);
231+
}
232+
233+
private void validateIssuer(OidcUser existingOidcUser, OidcIdToken idToken) {
234+
if (!idToken.getIssuer().toString().equals(existingOidcUser.getIdToken().getIssuer().toString())) {
235+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Invalid issuer",
236+
REFRESH_TOKEN_RESPONSE_ERROR_URI);
237+
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
238+
}
239+
}
240+
241+
private void validateSubject(OidcUser existingOidcUser, OidcIdToken idToken) {
242+
if (!idToken.getSubject().equals(existingOidcUser.getIdToken().getSubject())) {
243+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Invalid subject",
244+
REFRESH_TOKEN_RESPONSE_ERROR_URI);
245+
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
246+
}
247+
}
248+
249+
private void validateIssuedAt(OidcUser existingOidcUser, OidcIdToken idToken) {
250+
if (!idToken.getIssuedAt().isAfter(existingOidcUser.getIdToken().getIssuedAt().minus(this.clockSkew))) {
251+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Invalid issued at time",
252+
REFRESH_TOKEN_RESPONSE_ERROR_URI);
253+
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
254+
}
255+
}
256+
257+
private void validateAudience(OidcUser existingOidcUser, OidcIdToken idToken) {
258+
if (!isValidAudience(existingOidcUser, idToken)) {
259+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Invalid audience",
260+
REFRESH_TOKEN_RESPONSE_ERROR_URI);
261+
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
262+
}
263+
}
264+
265+
private boolean isValidAudience(OidcUser existingOidcUser, OidcIdToken idToken) {
266+
List<String> idTokenAudiences = idToken.getAudience();
267+
Set<String> oidcUserAudiences = new HashSet<>(existingOidcUser.getIdToken().getAudience());
268+
if (idTokenAudiences.size() != oidcUserAudiences.size()) {
269+
return false;
270+
}
271+
for (String audience : idTokenAudiences) {
272+
if (!oidcUserAudiences.contains(audience)) {
273+
return false;
274+
}
275+
}
276+
return true;
277+
}
278+
279+
private void validateAuthenticatedAt(OidcUser existingOidcUser, OidcIdToken idToken) {
280+
if (idToken.getAuthenticatedAt() == null) {
281+
return;
282+
}
283+
if (!idToken.getAuthenticatedAt().equals(existingOidcUser.getIdToken().getAuthenticatedAt())) {
284+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Invalid authenticated at time",
285+
REFRESH_TOKEN_RESPONSE_ERROR_URI);
286+
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
287+
}
288+
}
289+
290+
private void validateNonce(OidcUser existingOidcUser, OidcIdToken idToken) {
291+
if (!StringUtils.hasText(idToken.getNonce())) {
292+
return;
293+
}
294+
if (!idToken.getNonce().equals(existingOidcUser.getIdToken().getNonce())) {
295+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE, "Invalid nonce",
296+
REFRESH_TOKEN_RESPONSE_ERROR_URI);
297+
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
298+
}
299+
}
300+
301+
private Mono<Void> refreshSecurityContext(ServerWebExchange exchange, ClientRegistration clientRegistration,
302+
OAuth2AuthenticationToken authenticationToken, OidcUser oidcUser) {
303+
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
304+
.mapAuthorities(oidcUser.getAuthorities());
305+
OAuth2AuthenticationToken authenticationResult = new OAuth2AuthenticationToken(oidcUser, mappedAuthorities,
306+
clientRegistration.getRegistrationId());
307+
authenticationResult.setDetails(authenticationToken.getDetails());
308+
SecurityContextImpl securityContext = new SecurityContextImpl(authenticationResult);
309+
return this.serverSecurityContextRepository.save(exchange, securityContext);
310+
}
311+
312+
}

oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManager.java

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
3333
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider;
3434
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder;
35+
import org.springframework.security.oauth2.client.RefreshTokenReactiveOAuth2AuthorizationSuccessHandler;
3536
import org.springframework.security.oauth2.client.RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler;
3637
import org.springframework.security.oauth2.client.registration.ClientRegistration;
3738
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
@@ -85,6 +86,7 @@
8586
*
8687
* @author Joe Grandja
8788
* @author Phil Clay
89+
* @author Evgeniy Cheban
8890
* @since 5.2
8991
* @see ReactiveOAuth2AuthorizedClientManager
9092
* @see ReactiveOAuth2AuthorizedClientProvider
@@ -115,6 +117,8 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
115117

116118
private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper = new DefaultContextAttributesMapper();
117119

120+
private ReactiveOAuth2AuthorizationSuccessHandler refreshTokenSuccessHandler = new RefreshTokenReactiveOAuth2AuthorizationSuccessHandler();
121+
118122
private ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
119123

120124
private ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler;
@@ -132,15 +136,23 @@ public DefaultReactiveOAuth2AuthorizedClientManager(
132136
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
133137
this.clientRegistrationRepository = clientRegistrationRepository;
134138
this.authorizedClientRepository = authorizedClientRepository;
135-
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientRepository
136-
.saveAuthorizedClient(authorizedClient, principal,
137-
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName()));
139+
this.authorizationSuccessHandler = getAuthorizationSuccessHandler(authorizedClientRepository);
138140
this.authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
139141
(clientRegistrationId, principal, attributes) -> authorizedClientRepository.removeAuthorizedClient(
140142
clientRegistrationId, principal,
141143
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName())));
142144
}
143145

146+
private ReactiveOAuth2AuthorizationSuccessHandler getAuthorizationSuccessHandler(
147+
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
148+
return (authorizedClient, principal, attributes) -> {
149+
Mono<Void> saveAuthorizedClient = authorizedClientRepository.saveAuthorizedClient(authorizedClient,
150+
principal, (ServerWebExchange) attributes.get(ServerWebExchange.class.getName()));
151+
return saveAuthorizedClient.then(Mono.defer(() -> this.refreshTokenSuccessHandler
152+
.onAuthorizationSuccess(authorizedClient, principal, attributes)));
153+
};
154+
}
155+
144156
@Override
145157
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) {
146158
Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
@@ -274,6 +286,19 @@ public void setContextAttributesMapper(
274286
this.contextAttributesMapper = contextAttributesMapper;
275287
}
276288

289+
/**
290+
* Sets a {@link ReactiveOAuth2AuthorizationSuccessHandler} to use for handling
291+
* successful refresh token, defaults to
292+
* {@link RefreshTokenReactiveOAuth2AuthorizationSuccessHandler}.
293+
* @param refreshTokenSuccessHandler the
294+
* {@link ReactiveOAuth2AuthorizationSuccessHandler} to use
295+
* @since 7.1
296+
*/
297+
public void setRefreshTokenSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler refreshTokenSuccessHandler) {
298+
Assert.notNull(refreshTokenSuccessHandler, "refreshTokenSuccessHandler cannot be null");
299+
this.refreshTokenSuccessHandler = refreshTokenSuccessHandler;
300+
}
301+
277302
/**
278303
* Sets the handler that handles successful authorizations.
279304
*
@@ -318,10 +343,10 @@ public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest)
318343
return Mono.justOrEmpty(serverWebExchange)
319344
.switchIfEmpty(currentServerWebExchangeMono)
320345
.flatMap((exchange) -> {
321-
Map<String, Object> contextAttributes = Collections.emptyMap();
346+
Map<String, Object> contextAttributes = new HashMap<>();
347+
contextAttributes.put(ServerWebExchange.class.getName(), serverWebExchange);
322348
String scope = exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.SCOPE);
323349
if (StringUtils.hasText(scope)) {
324-
contextAttributes = new HashMap<>();
325350
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
326351
StringUtils.delimitedListToStringArray(scope, " "));
327352
}

0 commit comments

Comments
 (0)