Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

login automatically with Grails Spring Security

My Grails app is using the Spring Security plugin. I need to login a user programatically, and I don't have access to their password. I tried the following, which supposedly worked when using the Acegi plugin (an ancestor of the Spring Security plugin):

// automatically login a user and assign them the USER role. 
// In my app, the email address is also the username
GrantedAuthority[] auths = [new GrantedAuthorityImpl('USER')]
SecurityContextHolder.context.authentication 
        = new UsernamePasswordAuthenticationToken(email, 'unknown', auths)

It seems like this has almost worked, because if I call springSecurityService.principal after executing the above, I get back the email address of the automatically logged in user. However, if I call springSecurityService.currentUser I get an error. The root cause of this error is that:

SpringSecurityUtils.securityConfig.userLookup.userDomainClassName

returns "Person" which is not the name of my user class. The various tags such as <sec:loggedInUser> also don't work, presumably for the same reason.

I wonder if this problem is somehow related to the fact that I'm using pre-existing domain classes for user and role (rather than classes generated by the plugin)? If the user logs in by entering their username and password into the form (rather than programatically), everything seems to work fine.

Update

Following Burt's advice, I replaced the code above with:

springSecurityService.reauthenticate(email)

But I still get an error on these lines within SpringSecurityService.getCurrentUser()

String className = SpringSecurityUtils.securityConfig.userLookup.userDomainClassName
grailsApplication.getClassForName(className).get(principal.id)

Because className is set to "Person", rather than the name of my User class.

like image 651
Dónal Avatar asked Aug 18 '11 21:08

Dónal


1 Answers

If the user exists in the database use springSecurityService.reauthenticate() - see this link for Grails 2 or this link for Grails 3.

This method is designed to update the authentication when a user change has made it out of sync with the database, but it's also useful for this scenario where you want to force a valid authentication for an existing user but don't know the password.

like image 55
Burt Beckwith Avatar answered Nov 06 '22 20:11

Burt Beckwith