Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get principal user object in service methods

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?

like image 417
varun Avatar asked Aug 15 '13 09:08

varun


People also ask

What is SecurityContextHolder getContext () getAuthentication () getPrincipal ()?

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.

What does principal getName () return?

getName. Returns the name of this principal.

What method on the Authentication object can be used to obtain the username?

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.


1 Answers

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.

like image 56
LaurentG Avatar answered Sep 22 '22 15:09

LaurentG