From 0fea57d6a1e0bf25a47e854553e478704fa849ff Mon Sep 17 00:00:00 2001 From: Joe Grandja Date: Fri, 27 Sep 2019 14:46:39 -0400 Subject: [PATCH] Optimize SecurityReactorContextConfiguration Issue gh-7422 --- .../SecurityReactorContextConfiguration.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java index 8b6208c34a..12fa59a3ef 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java @@ -23,7 +23,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.util.CollectionUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import reactor.core.CoreSubscriber; @@ -70,7 +69,7 @@ class SecurityReactorContextConfiguration { Operators.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub)); Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, pub -> { - if (CollectionUtils.isEmpty(getContextAttributes())) { + if (!contextAttributesAvailable()) { // No need to decorate so return original Publisher return pub; } @@ -91,6 +90,22 @@ class SecurityReactorContextConfiguration { return new SecurityReactorContextSubscriber<>(delegate, getContextAttributes()); } + private static boolean contextAttributesAvailable() { + HttpServletRequest servletRequest = null; + HttpServletResponse servletResponse = null; + ServletRequestAttributes requestAttributes = + (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (requestAttributes != null) { + servletRequest = requestAttributes.getRequest(); + servletResponse = requestAttributes.getResponse(); + } + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null || servletRequest != null || servletResponse != null) { + return true; + } + return false; + } + private static Map getContextAttributes() { HttpServletRequest servletRequest = null; HttpServletResponse servletResponse = null;