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?
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
getName. Returns the name of this principal.
In order to get the current username, you first need a SecurityContext, which is obtained from SecurityContextHolder. This SecurityContext keep the user details in an Authentication object, which can be obtained by calling the getAuthentication() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With