Tuesday, January 19, 2010

Retrieving the current user from Acegi

The Grails Acegi plugin automatically puts the AuthenticateService into the Spring beans. This can be accessed in any controller simply by adding the member variable "authenticateService"

class MyController {
def authenticateService
...
}

The current user is retrieved with:
authenticateService.principal()

This returns an instance of:
org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserImpl

but of course we handle it dynamically:
def principal = authenticateService.principal()


The username can be retrieved by:
authenticateService.principal()?.getUsername()


Note, the "?" operator to prevent NullPointerException. The principal() is null when no one is logged in. You can always secure the page to prevent that but I usually develop unsecured and then add authentication before testing.

-Ben Hidalgo

No comments:

Post a Comment