Description
In order to support a lazy access of the SecurityContext
we should add methods to the SecurityContextHolder
that allow setting and getting a Supplier<SecurityContext>
. A benefit is that if it takes some work to obtain the SecurityContext
, the it is only looked up if necessary.
For example, currently the SecurityContext
is looked up from the HttpSession
for every page. When using distributed sessions (i.e. Spring Session + Redis) this is a lot of unnecessary overhead for accessing public css, javascript, and images. With these changes Spring Security can avoid accessing the HttpSession
for public resources like javascript, css, images, public html pages, etc.
The context would be set like this:
SecurityContextHolder.setDeferredContext(() -> securityContextRepository.loadContext(...));
Then code that wasn't sure if the SecurityContext
was needed could use:
Supplier<SecurityContext> deferredContext = SecurityContextHolder.getDeferredContext();
authorizationManager.check(() -> defferedContext.get().getAuthentication(), object);
If the AuthorizationManager
did not need to access the SecurityContext
(i.e. public invocation was allowed), it would not ever access the Supplier<Authentication>
and thus the Supplier<SecurityContext>
wouldn't be accessed either.
These changes will largely be internal and not impact users.
This is blocked by