'How does SecurityContextHolder.getContext().getAuthentication() work?

SecurityContextHolder.getContext().getAuthentication() obtains the currently authenticated principal, or an authentication request token, but in which context should we use it? Is it thread safe? For example, if we use a static helper method like:

public static UserEntity getCurrentUser() {
        return (UserEntity)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

Will it be safe to use? Or should we only use it under request scoped bean?



Solution 1:[1]

From Spring Security Document:

By default the SecurityContextHolder uses a ThreadLocal to store these details, which means that the SecurityContext is always available to methods in the same thread, even if the SecurityContext is not explicitly passed around as an argument to those methods. Using a ThreadLocal in this way is quite safe if care is taken to clear the thread after the present principal’s request is processed. Spring Security’s FilterChainProxy ensures that the SecurityContext is always cleared.

As per this blog :

The Java ThreadLocal class enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to the same ThreadLocal variable, the two threads cannot see each other's ThreadLocal variables. Thus, the Java ThreadLocal class provides a simple way to make code thread safe that would not otherwise be so.

Putting these together answers the question that is it safe to have a static util method to get the currently logged in user from SecurityContextHolder, Which is, yes it is safe.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deb