Reputation: 1003
For a Spring Security application using the default ThreadLocalSecurityContextHolderStrategy to save the Authentication
object into a ThreadLocal
variable, is it possible for any sort of error to arise where Spring Security won't be able to clear the ThreadLocal
before the request completes?
The SecurityContextPersistenceFilter performs the following:
Authentication
(from HttpSession
via HttpSessionSecurityContextRepository) to context (SecurityContextHolder
).Authentication
is cleared from SecurityContextHolder
so subsequent requests using the same ThreadLocal
do not have invalid data.In short, is there any scenario where #3 won't be able to complete because of application issue, timeout, or other? If so, how should an application ensure appropriate Authentication
detail for the current request (e.g. ensure data is valid for current request/user)?
Upvotes: 0
Views: 1576
Reputation: 159086
Since you linked to the source code, have a look at the source code for SecurityContextPersistenceFilter
:
...
try {
SecurityContextHolder.setContext(contextBeforeChainExecution);
chain.doFilter(holder.getRequest(), holder.getResponse());
}
finally {
SecurityContext contextAfterChainExecution = SecurityContextHolder
.getContext();
// Crucial removal of SecurityContextHolder contents - do this before anything
// else.
SecurityContextHolder.clearContext();
...
As you can see, the context is set inside the try
block, and is cleared right inside the finally
block, so it's impossible for the context to still be set once the request processing completes.
Upvotes: 2