Now that applications can use a SecurityContextHolderStrategy bean, there's value in assisting applications with what may be a sizeable transition away from using SecurityContextHolder.

There are some cases where an application may not want to copy the SecurityContextHolderStrategy bean into SecurityContextHolder's static field:

  • The application may not want to risk potential memory leaks from setting a bean to a static field
  • The application uses more than one application context, each with a SecurityContextHolderStrategy. Given that arrangement, it is undefined which bean will be set to the static field.
  • The application may want to discourage the use of static lookups.
  • The application may otherwise need more control over deciding what goes into the static field.

Given the foundational nature of SecurityContextHolder in Spring Security, it's likely that applications for a time will want to assume the above risks. As such, this should be property-driven.

One way to do this is to introduce useSecurityContextHolder into @EnableWebSecurity. It would default to true.

If useSecurityContextHolder is true, then Spring Security will look for a SecurityContextHolderStrategy bean and call SecurityContextHolder.setSecurityContextHolderStrategy. If it's false, then no action will be taken.

Comment From: kumper

Hello, any chance to have this implemented any time soon? It's open for over a year now and in my project we were also suffering from this. Finally we applied a workaround suggested in another issue, but it would be great to have it sorted out-of-the-box. BTW: we also have a shared security library, which sets reasonable security defaults, but then SecurityContextHolderStrategy is not shared between the components (filters in our case).

Comment From: landsman

Yeah, this is definitely pain.