Skip to content

Commit

Permalink
Merge branch '6.0.x'
Browse files Browse the repository at this point in the history
Closes gh-13309
  • Loading branch information
jzheaux committed Jun 12, 2023
2 parents cb6da94 + 5f26dae commit 00cf5ed
Show file tree
Hide file tree
Showing 14 changed files with 275 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -42,6 +42,7 @@
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;

/**
* Abstract base class for all of the {@code WebClientReactive*TokenResponseClient}s that
Expand Down Expand Up @@ -70,6 +71,8 @@ public abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T

private WebClient webClient = WebClient.builder().build();

private Converter<T, RequestHeadersSpec<?>> requestEntityConverter = this::validatingPopulateRequest;

private Converter<T, HttpHeaders> headersConverter = this::populateTokenRequestHeaders;

private Converter<T, MultiValueMap<String, String>> parametersConverter = this::populateTokenRequestParameters;
Expand All @@ -84,15 +87,7 @@ public abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T
public Mono<OAuth2AccessTokenResponse> getTokenResponse(T grantRequest) {
Assert.notNull(grantRequest, "grantRequest cannot be null");
// @formatter:off
return Mono.defer(() -> this.webClient.post()
.uri(clientRegistration(grantRequest).getProviderDetails().getTokenUri())
.headers((headers) -> {
HttpHeaders headersToAdd = getHeadersConverter().convert(grantRequest);
if (headersToAdd != null) {
headers.addAll(headersToAdd);
}
})
.body(createTokenRequestBody(grantRequest))
return Mono.defer(() -> this.requestEntityConverter.convert(grantRequest)
.exchange()
.flatMap((response) -> readTokenResponse(grantRequest, response))
);
Expand All @@ -106,6 +101,34 @@ public Mono<OAuth2AccessTokenResponse> getTokenResponse(T grantRequest) {
*/
abstract ClientRegistration clientRegistration(T grantRequest);

private RequestHeadersSpec<?> validatingPopulateRequest(T grantRequest) {
validateClientAuthenticationMethod(grantRequest);
return populateRequest(grantRequest);
}

private void validateClientAuthenticationMethod(T grantRequest) {
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
ClientAuthenticationMethod clientAuthenticationMethod = clientRegistration.getClientAuthenticationMethod();
boolean supportedClientAuthenticationMethod = clientAuthenticationMethod.equals(ClientAuthenticationMethod.NONE)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_POST);
if (!supportedClientAuthenticationMethod) {
throw new IllegalArgumentException(String.format(
"This class supports `client_secret_basic`, `client_secret_post`, and `none` by default. Client [%s] is using [%s] instead. Please use a supported client authentication method, or use `set/addParametersConverter` or `set/addHeadersConverter` to supply an instance that supports [%s].",
clientRegistration.getRegistrationId(), clientAuthenticationMethod, clientAuthenticationMethod));
}
}

private RequestHeadersSpec<?> populateRequest(T grantRequest) {
return this.webClient.post().uri(clientRegistration(grantRequest).getProviderDetails().getTokenUri())
.headers((headers) -> {
HttpHeaders headersToAdd = getHeadersConverter().convert(grantRequest);
if (headersToAdd != null) {
headers.addAll(headersToAdd);
}
}).body(createTokenRequestBody(grantRequest));
}

/**
* Populates the headers for the token request.
* @param grantRequest the grant request
Expand Down Expand Up @@ -280,6 +303,7 @@ final Converter<T, HttpHeaders> getHeadersConverter() {
public final void setHeadersConverter(Converter<T, HttpHeaders> headersConverter) {
Assert.notNull(headersConverter, "headersConverter cannot be null");
this.headersConverter = headersConverter;
this.requestEntityConverter = this::populateRequest;
}

/**
Expand Down Expand Up @@ -307,6 +331,7 @@ public final void addHeadersConverter(Converter<T, HttpHeaders> headersConverter
}
return headers;
};
this.requestEntityConverter = this::populateRequest;
}

/**
Expand All @@ -331,6 +356,7 @@ final Converter<T, MultiValueMap<String, String>> getParametersConverter() {
public final void setParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
this.parametersConverter = parametersConverter;
this.requestEntityConverter = this::populateRequest;
}

/**
Expand All @@ -357,6 +383,7 @@ public final void addParametersConverter(Converter<T, MultiValueMap<String, Stri
}
return parameters;
};
this.requestEntityConverter = this::populateRequest;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.security.oauth2.client.endpoint;

import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.util.Assert;

class ClientAuthenticationMethodValidatingRequestEntityConverter<T extends AbstractOAuth2AuthorizationGrantRequest>
implements Converter<T, RequestEntity<?>> {

private final Converter<T, RequestEntity<?>> delegate;

ClientAuthenticationMethodValidatingRequestEntityConverter(Converter<T, RequestEntity<?>> delegate) {
this.delegate = delegate;
}

@Override
public RequestEntity<?> convert(T grantRequest) {
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
ClientAuthenticationMethod clientAuthenticationMethod = clientRegistration.getClientAuthenticationMethod();
String registrationId = clientRegistration.getRegistrationId();
boolean supportedClientAuthenticationMethod = clientAuthenticationMethod.equals(ClientAuthenticationMethod.NONE)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_POST);
Assert.isTrue(supportedClientAuthenticationMethod, () -> String.format(
"This class supports `client_secret_basic`, `client_secret_post`, and `none` by default. Client [%s] is using [%s] instead. Please use a supported client authentication method, or use `setRequestEntityConverter` to supply an instance that supports [%s].",
registrationId, clientAuthenticationMethod, clientAuthenticationMethod));
return this.delegate.convert(grantRequest);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ public final class DefaultAuthorizationCodeTokenResponseClient

private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";

private Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>> requestEntityConverter = new OAuth2AuthorizationCodeGrantRequestEntityConverter();
private Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new OAuth2AuthorizationCodeGrantRequestEntityConverter());

private RestOperations restOperations;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -58,7 +58,8 @@ public final class DefaultClientCredentialsTokenResponseClient

private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";

private Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>> requestEntityConverter = new OAuth2ClientCredentialsGrantRequestEntityConverter();
private Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new OAuth2ClientCredentialsGrantRequestEntityConverter());

private RestOperations restOperations;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -56,7 +56,8 @@ public final class DefaultJwtBearerTokenResponseClient

private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";

private Converter<JwtBearerGrantRequest, RequestEntity<?>> requestEntityConverter = new JwtBearerGrantRequestEntityConverter();
private Converter<JwtBearerGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new JwtBearerGrantRequestEntityConverter());

private RestOperations restOperations;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -55,7 +55,8 @@ public final class DefaultRefreshTokenTokenResponseClient

private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";

private Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>> requestEntityConverter = new OAuth2RefreshTokenGrantRequestEntityConverter();
private Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new OAuth2RefreshTokenGrantRequestEntityConverter());

private RestOperations restOperations;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,28 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE
+ "the OAuth 2.0 Access Token Response");
}

// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest));
}

// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest));
}

private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest(ClientRegistration clientRegistration) {
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.clientId(clientRegistration.getClientId()).state("state-1234")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -379,6 +379,28 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}

// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest));
}

// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest));
}

private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -243,6 +243,26 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE
+ "retrieve the OAuth 2.0 Access Token Response");
}

// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest));
}

// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest));
}

private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -313,6 +313,28 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE
+ "retrieve the OAuth 2.0 Access Token Response");
}

// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest));
}

// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
this.accessToken, this.refreshToken);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest));
}

private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -500,4 +500,26 @@ public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenRespon

}

// gh-13144
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic")).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest).block());
}

// gh-13144
@Test
public void getTokenResponseWhenUnsupportedClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = authorizationCodeGrantRequest(
clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest).block());
}

}
Loading

0 comments on commit 00cf5ed

Please sign in to comment.