Login user for Integration test when using Jsecurity plugin

07 / Dec / 2009 by Amit Jain 0 comments

Hello Friends,

I was using Jsecurity plugin in my project. There was an action in a controller which needed logged in user information and I was finding it difficult to write an integration test for the same. Then Brent Fisher shared the following code which worked nicely for both services and controllers:

import org.jsecurity.SecurityUtils
import com.aps.domain.security.JsecUser
import org.jsecurity.subject.Subject

class MyControllerTests extends GrailsUnitTestCase {	

  protected void setUp() {
	super.setUp()	
	//following code sets admin as a logged in user				
	def subject = [isAuthenticated: true,
		       principal: "admin"
		      ] as Subject

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

Using metaclass, We changed the implementation of getPrincipal() and getSubject() to work in our way. So looking at this, I could see the power of a metaclass, which can be used to change or add new method implementations to an API which is not even accessible to us.

Cheers!

~~Amit Jain~~
amit@intelligrape.com
IntelliGrape Softwares

http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -