Spring Security: the same SecurityContext instance in multiple ThreadLocals, how does it work?

I have some questions about Spring Security 3.0.5 and SecurityContext. First of all, I am trying to complete what I know:

  • SecurityContextHolder saves SecurityContext
  • Between the request, the SecurityContext is stored in HttpSession
  • Start of request: SecurityContextHolder gets SecurityContext from HttpSession
  • End of request: SecurityContextHolder puts SecurityContext in HttpSession

  • During a request on the server, the SecurityContextHolder uses ThreadLocal. Throughout the application (the same request), you can access the SecurityContext

Now my question is ....

-> Two requests: SecurityContext instance will be split

How it works? I mean, SecurityContextHolder uses ThreadLocal for every request. 2 Request = 2 ThreadLocals

Each request executes: getSessionAttribute (SecurityContext) from HttpSession What happens if they work in SecurityContext? Is SecurityContext changed in all ThreadLocals?

As far as I know: yes (??)

How it works? How can they work in one copy? I mean, I really can’t imagine how two different threads with two different ThreadLocals can work in one instance?

API (ThreadLocal): This class provides local thread variables. These variables differ from their usual counterparts in that each thread that accesses it (using the get or set method) has its own, independently initialized copy of the variable.

I mean, here it is: copy! perhaps wrong and impossible for two threads to work on the same SecurityContext? But Spring Security Documentation says so!

It would be great if someone could explain this to me :-) Thank you!

+3
multithreading spring-security thread-local
source share
1 answer

Each thread has its own ThreadLocal value, but nothing prevents these values ​​from being equal. So, in this case, multiple threads will have links to the same SecurityContext instance.

This is usually not a problem, but if you want to change the security context, you can enable security copying, see SEC-356 .

+2
source share

All Articles