Address SecurityContextHolder memory leak

To get current context without creating a new context.
Creating a new context may cause ThreadLocal leak.

Closes gh-9841
This commit is contained in:
Hiroshi Shirosaki
2021-06-16 16:53:13 +09:00
committed by Josh Cummings
parent 898ba67098
commit 809ff883b0
6 changed files with 41 additions and 2 deletions

View File

@@ -36,6 +36,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
@@ -94,7 +95,12 @@ class SecurityReactorContextConfiguration {
}
private static boolean contextAttributesAvailable() {
return SecurityContextHolder.getContext().getAuthentication() != null
SecurityContext context = SecurityContextHolder.peekContext();
Authentication authentication = null;
if (context != null) {
authentication = context.getAuthentication();
}
return authentication != null
|| RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes;
}
@@ -107,7 +113,11 @@ class SecurityReactorContextConfiguration {
servletRequest = servletRequestAttributes.getRequest();
servletResponse = servletRequestAttributes.getResponse(); // possible null
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
SecurityContext context = SecurityContextHolder.peekContext();
Authentication authentication = null;
if (context != null) {
authentication = context.getAuthentication();
}
if (authentication == null && servletRequest == null) {
return Collections.emptyMap();
}