Spring Security’s SecurityContext is the cornerstone of authentication and authorization in Spring applications. It stores critical user details like authentication token, granted authorities, and principal information. However, when operations span multiple threads—common in asynchronous processing or reactive programming—propagating this context becomes a significant challenge. This guide explores various strategies to ensure your security context travels correctly across thread boundaries.
Understanding SecurityContext and ThreadLocal
At the heart of Spring Security lies the SecurityContextHolder, which uses a ThreadLocal strategy by default. This means each thread maintains its own isolated security context, which works perfectly in standard synchronous request-response cycles but breaks down when new threads are spawned.
The SecurityContextHolder supports three persistence strategies:
MODE_THREADLOCAL: Default strategy where context is bound to the current threadMODE_INHERITABLETHREADLOCAL: Context is inherited by child threads created by the current threadMODE_GLOBAL: Single context shared across all threads (rarely used in production)