Saturday, December 5, 2009

Getting a signed in user in Grails tests

I found this to be helpful. I just needed one more piece of information.

def subject = [
isAuthenticated: true,
principal: "admin"
] as Subject

SecurityUtils.metaClass.static.getSubject = {-> return subject }
Subject.metaClass.getPrincipal = {-> return "admin" }

This way, when I needed the user later on in the code, when I called getPrincipal, I got it. E.g.

JsecUser currentUser = JsecUser.findByUsername(SecurityUtils.getSubject()?.getPrincipal());

in reference to:

"void setUp() {       def subject = [           isAuthenticated: false,           ...       ] as Subject       SecurityUtils.metaClass.static.getSubject = {-> return subject }       ...   }"
- Nabble - grails - user - JSecurity-Plugin and Integration-Tests (view on Google Sidewiki)