I'm really new to Spring and Spring Security. I was reading about Spring Security and it came out the concept of principal, which should be the current logged user. But what if we have more than one current logged user? So, my question is, what exactly is then the principal in spring security?
I've read for example this tutorial:
http://www.mkyong.com/spring-security/get-current-logged-in-username-in-spring-security/
and they seem to take into account that there's just one current logged user, which isn't often the case.
How do I retrieve a specific user? And how do I differentiate between users that are doing requests?
Best Answer
The principal is the currently logged in user. However, you retrieve it through the security context which is bound to the current thread and as such it's also bound to the current request and its session.
SecurityContextHolder.getContext()
internally obtains the currentSecurityContext
implementation through aThreadLocal
variable. Because a request is bound to a single thread this will get you the context of the current request.To simplify you could say that the security context is in the session and contains user/principal and roles/authorities.
You don't. All APIs are designed to allow access to the user & session of the current request. Let user A be one of 100 currently authenticated users. If A issues a request against your server it will allocate one thread to process that request. If you then do
SecurityContextHolder.getContext().getAuthentication()
you do so in the context of this thread. By default from within that thread you don't have access to the context of user B which is processed by a different thread.You don't have to, that's what the Servlet container does for you.