Skip to content

Commit e4dcffa

Browse files
evgeniychebanjgrandja
authored andcommitted
Ensure ID Token is updated after refresh token (Reactive)
Closes gh-17188 Signed-off-by: Evgeniy Cheban <mister.cheban@gmail.com>
1 parent f52f097 commit e4dcffa

10 files changed

Lines changed: 1007 additions & 13 deletions

oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,8 @@ public final class RefreshTokenGrantBuilder implements Builder {
254254

255255
private ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient;
256256

257+
private ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
258+
257259
private Duration clockSkew;
258260

259261
private Clock clock;
@@ -274,6 +276,21 @@ public RefreshTokenGrantBuilder accessTokenResponseClient(
274276
return this;
275277
}
276278

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

0 commit comments

Comments
 (0)