Skip to content

Commit d2fe909

Browse files
committed
Add servlet support for OAuth 2.0 Token Exchange Grant
Issue gh-5199
1 parent 8cdd50a commit d2fe909

File tree

10 files changed

+1775
-0
lines changed

10 files changed

+1775
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
/*
2+
* Copyright 2002-2024 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.Clock;
20+
import java.time.Duration;
21+
import java.time.Instant;
22+
import java.util.function.Function;
23+
24+
import org.springframework.lang.Nullable;
25+
import org.springframework.security.oauth2.client.endpoint.DefaultTokenExchangeTokenResponseClient;
26+
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
27+
import org.springframework.security.oauth2.client.endpoint.TokenExchangeGrantRequest;
28+
import org.springframework.security.oauth2.client.registration.ClientRegistration;
29+
import org.springframework.security.oauth2.core.AuthorizationGrantType;
30+
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
31+
import org.springframework.security.oauth2.core.OAuth2Token;
32+
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
33+
import org.springframework.util.Assert;
34+
35+
/**
36+
* An implementation of an {@link OAuth2AuthorizedClientProvider} for the
37+
* {@link AuthorizationGrantType#TOKEN_EXCHANGE token-exchange} grant.
38+
*
39+
* @author Steve Riesenberg
40+
* @since 6.3
41+
* @see OAuth2AuthorizedClientProvider
42+
* @see DefaultTokenExchangeTokenResponseClient
43+
*/
44+
public final class TokenExchangeOAuth2AuthorizedClientProvider implements OAuth2AuthorizedClientProvider {
45+
46+
private OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient = new DefaultTokenExchangeTokenResponseClient();
47+
48+
private Function<OAuth2AuthorizationContext, OAuth2Token> subjectTokenResolver = this::resolveSubjectToken;
49+
50+
private Function<OAuth2AuthorizationContext, OAuth2Token> actorTokenResolver = (context) -> null;
51+
52+
private Duration clockSkew = Duration.ofSeconds(60);
53+
54+
private Clock clock = Clock.systemUTC();
55+
56+
/**
57+
* Attempt to authorize (or re-authorize) the
58+
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
59+
* {@code context}. Returns {@code null} if authorization (or re-authorization) is not
60+
* supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
61+
* authorization grant type} is not {@link AuthorizationGrantType#TOKEN_EXCHANGE
62+
* token-exchange} OR the {@link OAuth2AuthorizedClient#getAccessToken() access token}
63+
* is not expired.
64+
* @param context the context that holds authorization-specific state for the client
65+
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
66+
* supported
67+
*/
68+
@Override
69+
@Nullable
70+
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
71+
Assert.notNull(context, "context cannot be null");
72+
ClientRegistration clientRegistration = context.getClientRegistration();
73+
if (!AuthorizationGrantType.TOKEN_EXCHANGE.equals(clientRegistration.getAuthorizationGrantType())) {
74+
return null;
75+
}
76+
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
77+
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
78+
// If client is already authorized but access token is NOT expired than no
79+
// need for re-authorization
80+
return null;
81+
}
82+
OAuth2Token subjectToken = this.subjectTokenResolver.apply(context);
83+
if (subjectToken == null) {
84+
return null;
85+
}
86+
87+
OAuth2Token actorToken = this.actorTokenResolver.apply(context);
88+
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, subjectToken,
89+
actorToken);
90+
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, grantRequest);
91+
92+
return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
93+
tokenResponse.getAccessToken());
94+
}
95+
96+
private OAuth2Token resolveSubjectToken(OAuth2AuthorizationContext context) {
97+
if (context.getPrincipal().getPrincipal() instanceof OAuth2Token accessToken) {
98+
return accessToken;
99+
}
100+
return null;
101+
}
102+
103+
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
104+
TokenExchangeGrantRequest tokenExchangeGrantRequest) {
105+
try {
106+
return this.accessTokenResponseClient.getTokenResponse(tokenExchangeGrantRequest);
107+
}
108+
catch (OAuth2AuthorizationException ex) {
109+
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
110+
}
111+
}
112+
113+
private boolean hasTokenExpired(OAuth2Token token) {
114+
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
115+
}
116+
117+
/**
118+
* Sets the client used when requesting an access token credential at the Token
119+
* Endpoint for the {@code token-exchange} grant.
120+
* @param accessTokenResponseClient the client used when requesting an access token
121+
* credential at the Token Endpoint for the {@code token-exchange} grant
122+
*/
123+
public void setAccessTokenResponseClient(
124+
OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient) {
125+
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
126+
this.accessTokenResponseClient = accessTokenResponseClient;
127+
}
128+
129+
/**
130+
* Sets the resolver used for resolving the {@link OAuth2Token subject token}.
131+
* @param subjectTokenResolver the resolver used for resolving the {@link OAuth2Token
132+
* subject token}
133+
*/
134+
public void setSubjectTokenResolver(Function<OAuth2AuthorizationContext, OAuth2Token> subjectTokenResolver) {
135+
Assert.notNull(subjectTokenResolver, "subjectTokenResolver cannot be null");
136+
this.subjectTokenResolver = subjectTokenResolver;
137+
}
138+
139+
/**
140+
* Sets the resolver used for resolving the {@link OAuth2Token actor token}.
141+
* @param actorTokenResolver the resolver used for resolving the {@link OAuth2Token
142+
* actor token}
143+
*/
144+
public void setActorTokenResolver(Function<OAuth2AuthorizationContext, OAuth2Token> actorTokenResolver) {
145+
Assert.notNull(actorTokenResolver, "actorTokenResolver cannot be null");
146+
this.actorTokenResolver = actorTokenResolver;
147+
}
148+
149+
/**
150+
* Sets the maximum acceptable clock skew, which is used when checking the
151+
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
152+
* 60 seconds.
153+
*
154+
* <p>
155+
* An access token is considered expired if
156+
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
157+
* {@code clock#instant()}.
158+
* @param clockSkew the maximum acceptable clock skew
159+
*/
160+
public void setClockSkew(Duration clockSkew) {
161+
Assert.notNull(clockSkew, "clockSkew cannot be null");
162+
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
163+
this.clockSkew = clockSkew;
164+
}
165+
166+
/**
167+
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
168+
* token expiry.
169+
* @param clock the clock
170+
*/
171+
public void setClock(Clock clock) {
172+
Assert.notNull(clock, "clock cannot be null");
173+
this.clock = clock;
174+
}
175+
176+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
/*
2+
* Copyright 2002-2024 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.endpoint;
18+
19+
import java.util.Arrays;
20+
21+
import org.springframework.core.convert.converter.Converter;
22+
import org.springframework.http.RequestEntity;
23+
import org.springframework.http.ResponseEntity;
24+
import org.springframework.http.converter.FormHttpMessageConverter;
25+
import org.springframework.http.converter.HttpMessageConverter;
26+
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
27+
import org.springframework.security.oauth2.core.AuthorizationGrantType;
28+
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
29+
import org.springframework.security.oauth2.core.OAuth2Error;
30+
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
31+
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
32+
import org.springframework.util.Assert;
33+
import org.springframework.web.client.ResponseErrorHandler;
34+
import org.springframework.web.client.RestClientException;
35+
import org.springframework.web.client.RestOperations;
36+
import org.springframework.web.client.RestTemplate;
37+
38+
/**
39+
* The default implementation of an {@link OAuth2AccessTokenResponseClient} for the
40+
* {@link AuthorizationGrantType#TOKEN_EXCHANGE token-exchange} grant. This implementation
41+
* uses a {@link RestOperations} when requesting an access token credential at the
42+
* Authorization Server's Token Endpoint.
43+
*
44+
* @author Steve Riesenberg
45+
* @since 6.3
46+
* @see OAuth2AccessTokenResponseClient
47+
* @see TokenExchangeGrantRequest
48+
* @see OAuth2AccessTokenResponse
49+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8693#section-2.1">Section
50+
* 2.1 Request</a>
51+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8693#section-2.2">Section
52+
* 2.2 Response</a>
53+
*/
54+
public final class DefaultTokenExchangeTokenResponseClient
55+
implements OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> {
56+
57+
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
58+
59+
private Converter<TokenExchangeGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
60+
new TokenExchangeGrantRequestEntityConverter());
61+
62+
private RestOperations restOperations;
63+
64+
public DefaultTokenExchangeTokenResponseClient() {
65+
RestTemplate restTemplate = new RestTemplate(
66+
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
67+
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
68+
this.restOperations = restTemplate;
69+
}
70+
71+
@Override
72+
public OAuth2AccessTokenResponse getTokenResponse(TokenExchangeGrantRequest grantRequest) {
73+
Assert.notNull(grantRequest, "grantRequest cannot be null");
74+
RequestEntity<?> requestEntity = this.requestEntityConverter.convert(grantRequest);
75+
ResponseEntity<OAuth2AccessTokenResponse> responseEntity = getResponse(requestEntity);
76+
77+
return responseEntity.getBody();
78+
}
79+
80+
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> request) {
81+
try {
82+
return this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
83+
}
84+
catch (RestClientException ex) {
85+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
86+
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
87+
+ ex.getMessage(),
88+
null);
89+
throw new OAuth2AuthorizationException(oauth2Error, ex);
90+
}
91+
}
92+
93+
/**
94+
* Sets the {@link Converter} used for converting the
95+
* {@link TokenExchangeGrantRequest} to a {@link RequestEntity} representation of the
96+
* OAuth 2.0 Access Token Request.
97+
* @param requestEntityConverter the {@link Converter} used for converting to a
98+
* {@link RequestEntity} representation of the Access Token Request
99+
*/
100+
public void setRequestEntityConverter(
101+
Converter<TokenExchangeGrantRequest, RequestEntity<?>> requestEntityConverter) {
102+
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
103+
this.requestEntityConverter = requestEntityConverter;
104+
}
105+
106+
/**
107+
* Sets the {@link RestOperations} used when requesting the OAuth 2.0 Access Token
108+
* Response.
109+
*
110+
* <p>
111+
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
112+
* with the following:
113+
* <ol>
114+
* <li>{@link HttpMessageConverter}'s - {@link FormHttpMessageConverter} and
115+
* {@link OAuth2AccessTokenResponseHttpMessageConverter}</li>
116+
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
117+
* </ol>
118+
* @param restOperations the {@link RestOperations} used when requesting the Access
119+
* Token Response
120+
*/
121+
public void setRestOperations(RestOperations restOperations) {
122+
Assert.notNull(restOperations, "restOperations cannot be null");
123+
this.restOperations = restOperations;
124+
}
125+
126+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright 2002-2024 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.endpoint;
18+
19+
import org.springframework.security.oauth2.client.registration.ClientRegistration;
20+
import org.springframework.security.oauth2.core.AuthorizationGrantType;
21+
import org.springframework.security.oauth2.core.OAuth2Token;
22+
import org.springframework.util.Assert;
23+
24+
/**
25+
* A Token Exchange Grant request that holds the {@link OAuth2Token subject token} and
26+
* optional {@link OAuth2Token actor token}.
27+
*
28+
* @author Steve Riesenberg
29+
* @since 6.3
30+
* @see AbstractOAuth2AuthorizationGrantRequest
31+
* @see ClientRegistration
32+
* @see OAuth2Token
33+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8693#section-1.1">Section
34+
* 1.1 Delegation vs. Impersonation Semantics</a>
35+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8693#section-2.1">Section
36+
* 2.1 Request</a>
37+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8693#section-2.2">Section
38+
* 2.2 Response</a>
39+
*/
40+
public class TokenExchangeGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
41+
42+
private final OAuth2Token subjectToken;
43+
44+
private final OAuth2Token actorToken;
45+
46+
/**
47+
* Constructs a {@code TokenExchangeGrantRequest} using the provided parameters.
48+
* @param clientRegistration the client registration
49+
* @param subjectToken the subject token
50+
* @param actorToken the actor token
51+
*/
52+
public TokenExchangeGrantRequest(ClientRegistration clientRegistration, OAuth2Token subjectToken,
53+
OAuth2Token actorToken) {
54+
super(AuthorizationGrantType.TOKEN_EXCHANGE, clientRegistration);
55+
Assert.isTrue(AuthorizationGrantType.TOKEN_EXCHANGE.equals(clientRegistration.getAuthorizationGrantType()),
56+
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.TOKEN_EXCHANGE");
57+
Assert.notNull(subjectToken, "subjectToken cannot be null");
58+
this.subjectToken = subjectToken;
59+
this.actorToken = actorToken;
60+
}
61+
62+
/**
63+
* Returns the {@link OAuth2Token subject token}.
64+
* @return the {@link OAuth2Token subject token}
65+
*/
66+
public OAuth2Token getSubjectToken() {
67+
return this.subjectToken;
68+
}
69+
70+
/**
71+
* Returns the {@link OAuth2Token actor token}.
72+
* @return the {@link OAuth2Token actor token}
73+
*/
74+
public OAuth2Token getActorToken() {
75+
return this.actorToken;
76+
}
77+
78+
}

0 commit comments

Comments
 (0)