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

  • [x] gh-11028
  • [x] #11032
  • [ ] #11033

Comment From: linghengqian

Is this referring to the situation mentioned in https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html#servlet-authentication-securitycontextholder ? Should it change?

SecurityContext context = SecurityContextHolder.createEmptyContext(); 
Authentication authentication = new TestingAuthenticationToken("username", "password", "ROLE_USER");
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);

Comment From: rwinch

@linghengqian You would still be allowed to use the methods that you provided, but there will be additional methods to support delayed lookup of the SecurityContext. I've updated the description to provide more details.