it is famous to get the current user by calling :
springSecurityService.currentUser ;
Does Spring Ssecurity API save this object in HttpSession. if So, how to access to this object from session .
i.e: session['currentUser']
it is famous to get the current user by calling :
springSecurityService.currentUser ;
Does Spring Ssecurity API save this object in HttpSession. if So, how to access to this object from session .
i.e: session['currentUser']
It doesn't.
As you showed in your answer the
Principalis stored in the session, but that's theorg.springframework.security.core.userdetails.UserDetailsinstance that was created by theorg.springframework.security.core.userdetails.UserDetailsService. The default implementation of that in the plugin isgrails.plugin.springsecurity.userdetails.GrailsUserbut that's easily customized.The
UserDetailsinstance is typically a lightweight object, just containing the username and hashed password, a few locked/enabled booleans, and a collection ofGrantedAuthorityinstances to store role names. I often recommend that users extend this to also contain data that's useful but unlikely to change during a login session, e.g. full name, to avoid going to the database to retrieve it. Since theUserDetailsis stored in the session and easily accessible viaspringSecurityService.principalit's a great place to store data like this.But it is not the same thing as what's returned from
getCurrentUser()/currentUser- this is the GORM user/person domain class that was loaded by theUserDetailsServiceto create theUserDetailsinstance. It can have a lot more data associated with it, lazy-loaded hasMany collections, etc. It's often a rather large object that should not be stored in the session. Doing so does make its data conveniently available, but will affect scalability because you waste server memory and limit the number of concurrent sessions a server can have. And it's a disconnected Hibernate object, so to use it for most persistence-related actions requires that you reload the instance anyway, often withmerge(). That loads the whole thing from the database, so it's a lot more efficient to store the extra data you need in theUserDetails, along with the id of the instance so you can easily retrieve the instance as needed. That's whatgetCurrentUser()/currentUserdoes - it uses the id if it's available for aget()call, or the username for the equivalent of afindByUsername()call (which should be around the same cost if the username has a unique index).