Tuesday, May 4, 2010

session.user does not work with grails acegi plugin

Most tutorials and books introducing grails security concepts tell us that you can access information concerning the user by accessing the session.user object.

As I installed the acegi security plugin to get more advanced security features, this approach didn't work anymore. The documentation provided the solution.

If you are operating on GSPs you can use:

${loggedInUserInfo(field:'userRealName')}, which tells you the real name of the user. The field 'username' would provide you with the login name.

There are also the tags ${isLoggedIn} and ${isNotLoggedIn} to ensure that some content is only available to authenticated users.

But what happens if you want to access this information within a taglib or a controller? You have to include the authenticateService and use it:

Use authenticateService.isLoggedIn() to find out, whether a user is logged in, or not.

And use the following to access the user credentials:
def principal = authenticateService.principal()
println principal.getUsername()//get username
println principal.getAuthorities()//get authorities

Keep attention: If you want to obtain the User object you can no longer search for 'login', but for 'username':

User.findByUsername(principal.getUsername());

No comments:

Post a Comment