Skip to content

Commit 6759bc5

Browse files
committed
Add Token Exchange grant to demo-client sample
Issue spring-projectsgh-60
1 parent 7d65fcf commit 6759bc5

14 files changed

+689
-2
lines changed

Diff for: samples/demo-authorizationserver/src/main/java/sample/config/AuthorizationServerConfig.java

+10
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ public JdbcRegisteredClientRepository registeredClientRepository(JdbcTemplate jd
145145
.scope(OidcScopes.PROFILE)
146146
.scope("message.read")
147147
.scope("message.write")
148+
.scope("user.read")
148149
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
149150
.build();
150151

@@ -157,10 +158,19 @@ public JdbcRegisteredClientRepository registeredClientRepository(JdbcTemplate jd
157158
.scope("message.write")
158159
.build();
159160

161+
RegisteredClient tokenExchangeClient = RegisteredClient.withId(UUID.randomUUID().toString())
162+
.clientId("token-client")
163+
.clientSecret("{noop}token")
164+
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
165+
.authorizationGrantType(new AuthorizationGrantType("urn:ietf:params:oauth:grant-type:token-exchange"))
166+
.scope("message.read")
167+
.build();
168+
160169
// Save registered client's in db as if in-memory
161170
JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
162171
registeredClientRepository.save(registeredClient);
163172
registeredClientRepository.save(deviceClient);
173+
registeredClientRepository.save(tokenExchangeClient);
164174

165175
return registeredClientRepository;
166176
}

Diff for: samples/demo-client/src/main/java/sample/web/AuthorizationController.java

+20-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2020-2023 the original author or authors.
2+
* Copyright 2020-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -41,11 +41,14 @@
4141
public class AuthorizationController {
4242
private final WebClient webClient;
4343
private final String messagesBaseUri;
44+
private final String userMessagesBaseUri;
4445

4546
public AuthorizationController(WebClient webClient,
46-
@Value("${messages.base-uri}") String messagesBaseUri) {
47+
@Value("${messages.base-uri}") String messagesBaseUri,
48+
@Value("${user-messages.base-uri}") String userMessagesBaseUri) {
4749
this.webClient = webClient;
4850
this.messagesBaseUri = messagesBaseUri;
51+
this.userMessagesBaseUri = userMessagesBaseUri;
4952
}
5053

5154
@GetMapping(value = "/authorize", params = "grant_type=authorization_code")
@@ -96,6 +99,21 @@ public String clientCredentialsGrant(Model model) {
9699
return "index";
97100
}
98101

102+
@GetMapping(value = "/authorize", params = "grant_type=token_exchange")
103+
public String tokenExchangeGrant(Model model) {
104+
105+
String[] messages = this.webClient
106+
.get()
107+
.uri(this.userMessagesBaseUri)
108+
.attributes(clientRegistrationId("user-client-authorization-code"))
109+
.retrieve()
110+
.bodyToMono(String[].class)
111+
.block();
112+
model.addAttribute("messages", messages);
113+
114+
return "index";
115+
}
116+
99117
@GetMapping(value = "/authorize", params = "grant_type=device_code")
100118
public String deviceCodeGrant() {
101119
return "device-activate";

Diff for: samples/demo-client/src/main/resources/application.yml

+11
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ spring:
3838
authorization-grant-type: client_credentials
3939
scope: message.read,message.write
4040
client-name: messaging-client-client-credentials
41+
user-client-authorization-code:
42+
provider: spring
43+
client-id: messaging-client
44+
client-secret: secret
45+
authorization-grant-type: authorization_code
46+
redirect-uri: "http://127.0.0.1:8080/authorized"
47+
scope: user.read
48+
client-name: user-client-authorization-code
4149
messaging-client-device-code:
4250
provider: spring
4351
client-id: device-messaging-client
@@ -51,3 +59,6 @@ spring:
5159

5260
messages:
5361
base-uri: http://127.0.0.1:8090/messages
62+
63+
user-messages:
64+
base-uri: http://127.0.0.1:8091/user/messages

Diff for: samples/demo-client/src/main/resources/templates/page-templates.html

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
<ul class="dropdown-menu">
2626
<li><a class="dropdown-item" href="/authorize?grant_type=authorization_code" th:href="@{/authorize?grant_type=authorization_code}">Authorization Code</a></li>
2727
<li><a class="dropdown-item" href="/authorize?grant_type=client_credentials" th:href="@{/authorize?grant_type=client_credentials}">Client Credentials</a></li>
28+
<li><a class="dropdown-item" href="/authorize?grant_type=token_exchange" th:href="@{/authorize?grant_type=token_exchange}">Token Exchange</a></li>
2829
<li><a class="dropdown-item" href="/authorize?grant_type=device_code" th:href="@{/authorize?grant_type=device_code}">Device Code</a></li>
2930
</ul>
3031
</li>

Diff for: samples/users-resource/samples-users-resource.gradle

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
plugins {
2+
id "org.springframework.boot" version "3.2.2"
3+
id "io.spring.dependency-management" version "1.1.0"
4+
id "java"
5+
}
6+
7+
group = project.rootProject.group
8+
version = project.rootProject.version
9+
sourceCompatibility = "17"
10+
11+
repositories {
12+
mavenCentral()
13+
maven { url "https://repo.spring.io/milestone" }
14+
}
15+
16+
dependencies {
17+
implementation "org.springframework.boot:spring-boot-starter-web"
18+
implementation "org.springframework.boot:spring-boot-starter-security"
19+
implementation "org.springframework.boot:spring-boot-starter-oauth2-resource-server"
20+
implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* Copyright 2020-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+
package sample;
17+
18+
import org.springframework.boot.SpringApplication;
19+
import org.springframework.boot.autoconfigure.SpringBootApplication;
20+
21+
/**
22+
* @author Steve Riesenberg
23+
* @since 1.3
24+
*/
25+
@SpringBootApplication
26+
public class UsersResourceApplication {
27+
28+
public static void main(String[] args) {
29+
SpringApplication.run(UsersResourceApplication.class, args);
30+
}
31+
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright 2020-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+
package sample.authorization;
17+
18+
import java.util.Arrays;
19+
20+
import org.springframework.core.convert.converter.Converter;
21+
import org.springframework.http.RequestEntity;
22+
import org.springframework.http.ResponseEntity;
23+
import org.springframework.http.converter.FormHttpMessageConverter;
24+
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
25+
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
26+
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
27+
import org.springframework.security.oauth2.core.OAuth2Error;
28+
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
29+
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
30+
import org.springframework.util.Assert;
31+
import org.springframework.web.client.RestClientException;
32+
import org.springframework.web.client.RestOperations;
33+
import org.springframework.web.client.RestTemplate;
34+
35+
/**
36+
* @author Steve Riesenberg
37+
* @since 1.3
38+
*/
39+
public final class DefaultTokenExchangeTokenResponseClient
40+
implements OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> {
41+
42+
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
43+
44+
private Converter<TokenExchangeGrantRequest, RequestEntity<?>> requestEntityConverter = new TokenExchangeGrantRequestEntityConverter();
45+
46+
private RestOperations restOperations;
47+
48+
public DefaultTokenExchangeTokenResponseClient() {
49+
RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(),
50+
new OAuth2AccessTokenResponseHttpMessageConverter()));
51+
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
52+
this.restOperations = restTemplate;
53+
}
54+
55+
@Override
56+
public OAuth2AccessTokenResponse getTokenResponse(TokenExchangeGrantRequest tokenExchangeGrantRequest) {
57+
Assert.notNull(tokenExchangeGrantRequest, "tokenExchangeGrantRequest cannot be null");
58+
RequestEntity<?> requestEntity = this.requestEntityConverter.convert(tokenExchangeGrantRequest);
59+
ResponseEntity<OAuth2AccessTokenResponse> responseEntity = getResponse(requestEntity);
60+
61+
return responseEntity.getBody();
62+
}
63+
64+
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> requestEntity) {
65+
try {
66+
return this.restOperations.exchange(requestEntity, OAuth2AccessTokenResponse.class);
67+
} catch (RestClientException ex) {
68+
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
69+
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
70+
+ ex.getMessage(), null);
71+
throw new OAuth2AuthorizationException(oauth2Error, ex);
72+
}
73+
}
74+
75+
public void setRequestEntityConverter(Converter<TokenExchangeGrantRequest, RequestEntity<?>> requestEntityConverter) {
76+
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
77+
this.requestEntityConverter = requestEntityConverter;
78+
}
79+
80+
public void setRestOperations(RestOperations restOperations) {
81+
Assert.notNull(restOperations, "restOperations cannot be null");
82+
this.restOperations = restOperations;
83+
}
84+
85+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* Copyright 2020-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+
package sample.authorization;
17+
18+
import org.springframework.security.oauth2.client.endpoint.AbstractOAuth2AuthorizationGrantRequest;
19+
import org.springframework.security.oauth2.client.registration.ClientRegistration;
20+
import org.springframework.security.oauth2.core.AuthorizationGrantType;
21+
import org.springframework.util.Assert;
22+
23+
/**
24+
* @author Steve Riesenberg
25+
* @since 1.3
26+
*/
27+
public final class TokenExchangeGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
28+
29+
static final AuthorizationGrantType TOKEN_EXCHANGE = new AuthorizationGrantType(
30+
"urn:ietf:params:oauth:grant-type:token-exchange");
31+
32+
private final String subjectToken;
33+
34+
private final String actorToken;
35+
36+
public TokenExchangeGrantRequest(ClientRegistration clientRegistration, String subjectToken,
37+
String actorToken) {
38+
super(TOKEN_EXCHANGE, clientRegistration);
39+
Assert.hasText(subjectToken, "subjectToken cannot be empty");
40+
if (actorToken != null) {
41+
Assert.hasText(actorToken, "actorToken cannot be empty");
42+
}
43+
this.subjectToken = subjectToken;
44+
this.actorToken = actorToken;
45+
}
46+
47+
public String getSubjectToken() {
48+
return this.subjectToken;
49+
}
50+
51+
public String getActorToken() {
52+
return this.actorToken;
53+
}
54+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright 2020-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+
package sample.authorization;
17+
18+
import org.springframework.core.convert.converter.Converter;
19+
import org.springframework.http.HttpHeaders;
20+
import org.springframework.http.RequestEntity;
21+
import org.springframework.security.oauth2.client.registration.ClientRegistration;
22+
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
23+
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
24+
import org.springframework.util.CollectionUtils;
25+
import org.springframework.util.LinkedMultiValueMap;
26+
import org.springframework.util.MultiValueMap;
27+
import org.springframework.util.StringUtils;
28+
29+
/**
30+
* @author Steve Riesenberg
31+
* @since 1.3
32+
*/
33+
public class TokenExchangeGrantRequestEntityConverter implements Converter<TokenExchangeGrantRequest, RequestEntity<?>> {
34+
35+
private static final String REQUESTED_TOKEN_TYPE = "requested_token_type";
36+
37+
private static final String SUBJECT_TOKEN = "subject_token";
38+
39+
private static final String SUBJECT_TOKEN_TYPE = "subject_token_type";
40+
41+
private static final String ACTOR_TOKEN = "actor_token";
42+
43+
private static final String ACTOR_TOKEN_TYPE = "actor_token_type";
44+
45+
private static final String ACCESS_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:access_token";
46+
47+
@Override
48+
public RequestEntity<?> convert(TokenExchangeGrantRequest grantRequest) {
49+
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
50+
51+
HttpHeaders headers = new HttpHeaders();
52+
if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
53+
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
54+
}
55+
56+
MultiValueMap<String, Object> requestParameters = new LinkedMultiValueMap<>();
57+
requestParameters.add(OAuth2ParameterNames.GRANT_TYPE, grantRequest.getGrantType().getValue());
58+
requestParameters.add(REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE);
59+
requestParameters.add(SUBJECT_TOKEN, grantRequest.getSubjectToken());
60+
requestParameters.add(SUBJECT_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE);
61+
if (StringUtils.hasText(grantRequest.getActorToken())) {
62+
requestParameters.add(ACTOR_TOKEN, grantRequest.getActorToken());
63+
requestParameters.add(ACTOR_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE);
64+
}
65+
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
66+
requestParameters.add(OAuth2ParameterNames.SCOPE,
67+
StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
68+
}
69+
if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
70+
requestParameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
71+
requestParameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
72+
}
73+
74+
String tokenEndpointUri = clientRegistration.getProviderDetails().getTokenUri();
75+
return RequestEntity.post(tokenEndpointUri).headers(headers).body(requestParameters);
76+
}
77+
78+
}

0 commit comments

Comments
 (0)