Summary
NOTE: This was originally brought up as a question in gh-8322 this ticket is to resolve that question
Ideally we would provide Authentication implementations that are immutable to avoid race conditions. However, for historical reasons it is unfortunate that both Authentication and SecurityContext are mutable.
We should look into how we can make both of these immutable
Comment From: jzheaux
Regarding SecurityContext, I think SecurityContextImpl should add a constructor that takes Authentication, and its setAuthentication method should be deprecated.
Then an application could do:
SecurityContext context = new SecurityContextImpl(authentication);
SecurityContextHolder.setContext(context);
whenever the authentication needs to change.
It's not really clear to me why the SecurityContextHolderStrategy has a createEmptyContext (instead of apps constructing a security context directly); however, if it's important to route construction through SecurityContextHolder, then adding something like SecurityContextHolder#createContext(Authentication) could address that.
Comment From: SpiReCZ
Security Context was already made immutable in https://github.com/spring-projects/spring-security/issues/10032 and it created issue in: https://github.com/spring-projects/spring-security/issues/11100
Comment From: rwinch
Given this is potentially a breaking change, we should consider it for 6.0.x