Skip to content

Commit

Permalink
Fix ThreadLocal leak with SecurityContextHolder
Browse files Browse the repository at this point in the history
Use SecurityContextHolder.peekContext() so that it doesn't create
an empty object in ThreadLocal.
  • Loading branch information
shirosaki committed Jun 16, 2021
1 parent c6670b8 commit aeb6f5f
Showing 1 changed file with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
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;
Expand Down Expand Up @@ -94,7 +95,12 @@ <T> CoreSubscriber<T> createSubscriberIfNecessary(CoreSubscriber<T> delegate) {
}

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;
}

Expand All @@ -107,7 +113,11 @@ private static Map<Object, Object> getContextAttributes() {
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();
}
Expand Down

0 comments on commit aeb6f5f

Please sign in to comment.