Ive some questions about Spring Security 3.0.5 and the SecurityContext. First of all, Ill try to conclude what I know:
- SecurityContextHolder stores SecurityContext
- Between Request, SecurityContext is stored in HttpSession
- Begin of Request: SecurityContextHolder gets SecurityContext from HttpSession
End of Request: SecurityContextHolder puts SecurityContext in HttpSession
During the Request, on the server, SecurityContextHolder uses a ThreadLocal. Everywhere in the application (same request), the SecurityContext can be accessed
Now my question....
--> Two Requests: the SecurityContext-instance will be shared
How does this work? I mean, SecurityContextHolder uses a ThreadLocal for Each Request. 2 Request = 2 ThreadLocals
Each request does: getSessionAttribute (SecurityContext) from HttpSession What happens if they work on the SecurityContext? Is the SecurityContext changed in all ThreadLocals?
As far as I know: yes (??)
How does this work? How can they work on the same instance? I mean, I really cant imagine how two different threads with two different ThreadLocals can work on the same instance?
API (ThreadLocal): This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.
I mean, thats it: copy! maybe Im wrong and its not possible for two threads to work on the same SecurityContext? But Spring Security Documentation says so!
Would be great if someone could explain that to me :-) Thank you!
Each thread has its own value of
ThreadLocal
, but nothing prevents these values from being equal. So, in this case multiple thread would have references to the same instance ofSecurityContext
.Usually it's not a problem, but if you want to modify security context, you can enable defensive copying, see SEC-356.