I use SecurityContextHolder and a custom UserDetailsService to obtain UserDetails from SecurityContextHolder:
Object o = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetailsDTO user = (UserDetailsDTO) o;
I left out the null checks, etc., but that's the idea. I'm using this in an @Around pointcut of an @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 a ThreadLocal by default, but the pointcut stuff also seems to have some sort of encapsulated threading logic.
Is it possible that there could be user collision (i.e. access UserA from one session for a UserB audit event in another concurrent session), or possibly a null user altogether.
Is there a better way to obtain the credentials/user profile?