Is the SecurityContextHolder thread safe?

I use a SecurityContextHolder and a custom UserDetailsService to get UserDetails from a SecurityContextHolder :

 Object o = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserDetailsDTO user = (UserDetailsDTO) o; 

I left zero checks, etc., but this is an idea. I use this in pointcut @Around for @Aspect :

 @Around("execution(* user.service.*.*(..))") public Object audit(ProceedingJoinPoint call) throws Throwable { // get user id // add audit row in db } 

Looking at the SecurityContextHolder class, it uses ThreadLocal by default, but the pointcut stuff also seems to have some kind of encapsulated thread logic.

Is it possible that a user conflict could arise (i.e., gain UserA access from one session for a UserB audit event in another concurrent session), or possibly a null user.

Is there a better way to get user credentials / profile?

+6
java spring spring-mvc spring-security
source share
3 answers

Yes, it is stream safe with the default strategy ( MODE_THREADLOCAL ) (until you try to change the strategy on the fly). However, if you want the child threads to inherit the SecurityContext parent thread, you must set MODE_INHERITABLETHREADLOCAL .

Also, aspects do not have โ€œthread logicโ€; they run in the same thread as the recommended method.

+5
source share

in general, ThreadLocal will not be friendly in the global cached thread pool. In the default pool of cached threads, ExecutorService (Executors.newCachedThreadPool ()) will either be the initial ThreadLocal storage thread or empty. In this situation, setting MODE_INHERITABLETHREADLOCAL will not change anything unless the cached threadpool is initialized for each request, which would be a pretty bad use. Make sure any underlying structures or libraries do not use Executors.newCachedThreadPool () to provide a thread pool for you.

+1
source share

Yes, it is thread safe. You should just call SecurityContextHolder.getContext (). GetAuthentication (). GetName ()

-one
source share

All Articles