From 9593f9cae2f91c51d349532675f70ad9bd326fd0 Mon Sep 17 00:00:00 2001 From: Phil Clay Date: Wed, 27 Mar 2019 15:39:00 -0700 Subject: [PATCH] Defer downstream filter execution if no OAuth2AuthorizedClient is found Prior to this change, ServerOAuth2AuthorizedClientExchangeFilterFunction would invoke next.exchange: - first at assembly time inside the .switchIfEmpty call. - second at execution time inside .flatMap when a OAuth2AuthorizedClient is found. While this double-call should not technically cause any functional problems, since the Mono returned by the first call will not be subscribed if a OAuth2AuthorizedClient is found, it does result in a lot of unnecessary execution and object creation. There is no technical need to invoke the downstream filters twice. This change defers the call inside .switchIfEmpty, so that it will only execute at execution time if an OAuth2AuthorizedClient is not found. After this change, ServerOAuth2AuthorizedClientExchangeFilterFunction will not invoke next.exchange at assembly time, and will only execute next.exchange once per subscription at execution time. Fixes gh-6719 --- .../ServerOAuth2AuthorizedClientExchangeFilterFunction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java index 89bed5a5b9..c8da1dca42 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java @@ -227,7 +227,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements return authorizedClient(request, next) .map(authorizedClient -> bearer(request, authorizedClient)) .flatMap(next::exchange) - .switchIfEmpty(next.exchange(request)); + .switchIfEmpty(Mono.defer(() -> next.exchange(request))); } private Mono authorizedClient(ClientRequest request, ExchangeFunction next) {