Skip to content

Commit 0681e72

Browse files
committed
Add support for OAuth 2.0 Token Exchange Grant
Issue spring-projectsgh-5199
1 parent f8ff056 commit 0681e72

File tree

6 files changed

+508
-0
lines changed

6 files changed

+508
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
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+
if (authorizedClient != null && authorizedClient.getRefreshToken() != null) {
83+
// If client is already authorized but access token is expired and a
84+
// refresh token is available, delegate to refresh_token.
85+
return null;
86+
}
87+
88+
OAuth2Token subjectToken = this.subjectTokenResolver.apply(context);
89+
if (subjectToken == null) {
90+
return null;
91+
}
92+
93+
OAuth2Token actorToken = this.actorTokenResolver.apply(context);
94+
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, subjectToken,
95+
actorToken);
96+
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, grantRequest);
97+
98+
return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
99+
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
100+
}
101+
102+
private OAuth2Token resolveSubjectToken(OAuth2AuthorizationContext context) {
103+
if (context.getPrincipal().getPrincipal() instanceof OAuth2Token accessToken) {
104+
return accessToken;
105+
}
106+
return null;
107+
}
108+
109+
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
110+
TokenExchangeGrantRequest tokenExchangeGrantRequest) {
111+
try {
112+
return this.accessTokenResponseClient.getTokenResponse(tokenExchangeGrantRequest);
113+
}
114+
catch (OAuth2AuthorizationException ex) {
115+
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
116+
}
117+
}
118+
119+
private boolean hasTokenExpired(OAuth2Token token) {
120+
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
121+
}
122+
123+
/**
124+
* Sets the client used when requesting an access token credential at the Token
125+
* Endpoint for the {@code token-exchange} grant.
126+
* @param accessTokenResponseClient the client used when requesting an access token
127+
* credential at the Token Endpoint for the {@code token-exchange} grant
128+
*/
129+
public void setAccessTokenResponseClient(
130+
OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient) {
131+
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
132+
this.accessTokenResponseClient = accessTokenResponseClient;
133+
}
134+
135+
/**
136+
* Sets the resolver used for resolving the {@link OAuth2Token subject token}.
137+
* @param subjectTokenResolver the resolver used for resolving the {@link OAuth2Token
138+
* subject token}
139+
*/
140+
public void setSubjectTokenResolver(Function<OAuth2AuthorizationContext, OAuth2Token> subjectTokenResolver) {
141+
Assert.notNull(subjectTokenResolver, "subjectTokenResolver cannot be null");
142+
this.subjectTokenResolver = subjectTokenResolver;
143+
}
144+
145+
/**
146+
* Sets the resolver used for resolving the {@link OAuth2Token actor token}.
147+
* @param actorTokenResolver the resolver used for resolving the {@link OAuth2Token
148+
* actor token}
149+
*/
150+
public void setActorTokenResolver(Function<OAuth2AuthorizationContext, OAuth2Token> actorTokenResolver) {
151+
Assert.notNull(actorTokenResolver, "actorTokenResolver cannot be null");
152+
this.actorTokenResolver = actorTokenResolver;
153+
}
154+
155+
/**
156+
* Sets the maximum acceptable clock skew, which is used when checking the
157+
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
158+
* 60 seconds.
159+
*
160+
* <p>
161+
* An access token is considered expired if
162+
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
163+
* {@code clock#instant()}.
164+
* @param clockSkew the maximum acceptable clock skew
165+
*/
166+
public void setClockSkew(Duration clockSkew) {
167+
Assert.notNull(clockSkew, "clockSkew cannot be null");
168+
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
169+
this.clockSkew = clockSkew;
170+
}
171+
172+
/**
173+
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
174+
* token expiry.
175+
* @param clock the clock
176+
*/
177+
public void setClock(Clock clock) {
178+
Assert.notNull(clock, "clock cannot be null");
179+
this.clock = clock;
180+
}
181+
182+
}
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 tokenExchangeGrantRequest) {
73+
Assert.notNull(tokenExchangeGrantRequest, "tokenExchangeGrantRequest cannot be null");
74+
RequestEntity<?> requestEntity = this.requestEntityConverter.convert(tokenExchangeGrantRequest);
75+
ResponseEntity<OAuth2AccessTokenResponse> responseEntity = getResponse(requestEntity);
76+
77+
return responseEntity.getBody();
78+
}
79+
80+
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> requestEntity) {
81+
try {
82+
return this.restOperations.exchange(requestEntity, 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,76 @@
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 JwtBearerGrantRequest} 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.notNull(subjectToken, "subjectToken cannot be null");
56+
this.subjectToken = subjectToken;
57+
this.actorToken = actorToken;
58+
}
59+
60+
/**
61+
* Returns the {@link OAuth2Token subject token}.
62+
* @return the {@link OAuth2Token subject token}
63+
*/
64+
public OAuth2Token getSubjectToken() {
65+
return this.subjectToken;
66+
}
67+
68+
/**
69+
* Returns the {@link OAuth2Token actor token}.
70+
* @return the {@link OAuth2Token actor token}
71+
*/
72+
public OAuth2Token getActorToken() {
73+
return this.actorToken;
74+
}
75+
76+
}

0 commit comments

Comments
 (0)