newbie
newbie

Reputation: 119

grails - get current user globally

I'm new in using Spring Security plug-in for my grails app. Here's my code in getting the current user logged in.

String username = getPrincipal().username

But the thing is I'm writing this line in every action to get the current user. Is there a way to globally get the current user? And use it in every action without declaring it again and again?

Upvotes: 2

Views: 1149

Answers (2)

Anton Hlinisty
Anton Hlinisty

Reputation: 1467

If you need to get user object I suggest you to retrieve "fresh" (taken from the DB) user instance each time using the injected before springSecurityService:

springSecurityService.principal.username

But if you need only a username - you could create a session-scoped bean and populate it with username at the creation time:

resources.groovy:

...
userNameHolder(UserNameHolder) { bean ->
    bean.scope = 'session'
    springSecurityService = ref("springSecurityService")
}
...

And:

class UserNameHolder {
    def springSecurityService

    String username = springSecurityService.principal.username

    String getUsername() {
        username
    }
}

Then you should inject UserNameHolder to the places needed and retrieve username:

class SomeService {

    def userNameHolder

    void someMethod() {
        ...
        userNameHolder.username
        ...
    }
    ...
}

Enjoy!

UPD:

You could do almost the same by putting username into the HTTPSession, but it would be much less controlable and testable. So I strongly recommend you to use a session-scoped bean.

Upvotes: 0

rgrebski
rgrebski

Reputation: 2584

You can do it in 2 ways:
1) You can inject SpringSecurityService anywhere you want, simply in any controller/service:

SpringSecurityService springSecurityService

def someMethod(){
   springSecurityService.principal
}

2) You can use SecurityContextHolder:

def someMethod(){
   SecurityContextHolder.context.authentication?.principal
}

I suggest using option 1, it makes testing easier etc.

Upvotes: 3

Related Questions