trebor
trebor

Reputation: 1003

Is there any scenario where SecurityContext won't get cleared from ThreadLocal after a request?

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:

  1. Loads Authentication (from HttpSession via HttpSessionSecurityContextRepository) to context (SecurityContextHolder).
  2. Filter chain is invoked for continued request execution by application.
  3. 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

Answers (1)

Andreas
Andreas

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

Related Questions