Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Spring Security (get current user)

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?

like image 700
dre Avatar asked Apr 24 '14 21:04

dre


3 Answers

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).

like image 63
Dónal Avatar answered Nov 13 '22 21:11

Dónal


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.

like image 43
Joshua Moore Avatar answered Nov 13 '22 21:11

Joshua Moore


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.

like image 2
Neal Avatar answered Nov 13 '22 23:11

Neal