Alex Rivera | Logout

login automatically with Grails Spring Security

Asked 2011-08-18T21:12:50.427
14

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 cl
Edit
Report

1 Answer

20

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.

answered 2011-08-18T21:37:09.253

Your Answer