Get principal user object in service methods
spring, spring-mvc, spring-security
Solution
I think that the best approach would be to use the `SecurityContextHolder`.
Principal principal = SecurityContextHolder.getContext().getAuthentication();
Spring explains how it works in the documentation:
The most fundamental object is SecurityContextHolder. This is where we store details of the present security context of the application, which includes details of the principal currently using the application. By default the SecurityContextHolder uses a ThreadLocal to store these details, which means that the security context is always available to methods in the same thread of execution, even if the security context 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. Of course, Spring Security takes care of this for you automatically so there is no need to worry about it.
Since it uses a `ThreadLocal` to store the current authentication, you will not have any thread safety problem.
Problem
In my spring MVC application i want to access `Principal` object created by spring security in my service layer. I thought about injecting it in my service classes, but I am sure it will not be thread safe. Other option I am thinking, is to pass it to all service methods as argument but this do not look very clean to me. What would be the better way to do this?