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 Principal
is stored in the session, but that's the org.springframework.security.core.userdetails.UserDetails
instance that was created by the org.springframework.security.core.userdetails.UserDetailsService
. The default implementation of that in the plugin is grails.plugin.springsecurity.userdetails.GrailsUser
but that's easily customized.
The UserDetails
instance is typically a lightweight object, just containing the username and hashed password, a few locked/enabled booleans, and a collection of GrantedAuthority
instances 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 the UserDetails
is stored in the session and easily accessible via springSecurityService.principal
it'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 the UserDetailsService
to create the UserDetails
instance. 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 with merge()
. That loads the whole thing from the database, so it's a lot more efficient to store the extra data you need in the UserDetails
, along with the id of the instance so you can easily retrieve the instance as needed. That's what getCurrentUser()
/currentUser
does - it uses the id if it's available for a get()
call, or the username for the equivalent of a findByUsername()
call (which should be around the same cost if the username has a unique index).