Is there ever a case for:
def user = User.get(springSecurityService.principal.id)
over
def user = springSecurityService.currentUser
All I can think of is preventing lazy inits or ensuring data you are currently operating on is not stale?
In practical terms, I don't see much difference between these two. I would be inclined to use
def user = springSecurityService.currentUser
Because it's slightly shorter that the other form, it's what the plugin docs recommend, and there might be some additional caching of the user within plugin (beyond the caching already provided by Hibernate).
Well, there is a slight difference between the two. The documentation points this out.
currentUser
will always return the domain instance of the currently logged in user.
principal
on the other hand, retrieves the currently logged in user's Principal
. If authenticated, the principal will be a grails.plugin.springsecurity.userdetails.GrailsUser
, unless you have created a custom UserDetailsService
, in which case it will be whatever implementation of UserDetails
you use there.
If not authenticated and the AnonymousAuthenticationFilter
is active (true by default) then a standard org.springframework.security.core.userdetails.User
is used.
Hope that helps clear things up.
We just encountered a case where code was using currentUser and failing because there was no User record for the User domain. In our case, principal.username worked because we had a custom UserDetailsService that was creating a GrailsUser on the fly if one didn't exist in the User table.
So the distinction is important.
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