jsecurity plugin « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ jsecurity plugin ’

Programmatically logging in user in jsecurity plugin

Posted by Bhagwat Kumar on March 4th, 2010

In our current project we are using jsecurity plugin and some of our bootstrap code required a user to be logged in. I found a nice blog http://www.intelligrape.com/blog/?p=335 on this topic but it was using groovy metaprogramming to override the normal behaviour of SecurityUtils.getSubject() which is suitable for test environment.

After a few minutes of digging into jsecurity plugin we found an easy solution :-

class MyController{
  def jsecSecurityManager
 
  def myAction={
        def authToken = new org.jsecurity.authc.UsernamePasswordToken("bootstrapuser", "password")
        jsecSecurityManager.login(authToken)
 
	/*
	Your code here that depends on logged in user.
	e.g. String userId=org.jsecurity.SecurityUtils.getSubject()?.getPrincipal()
	*/
 
   }
}

It worked for us.Hope it will save your time too.

~~~~Bhagwt Kumar~~~~
bhagwat@intelligrape.com
IntelliGrape Software

  • Share/Bookmark
Posted in Grails

Login user for Integration test when using Jsecurity plugin

Posted by Amit Jain on December 7th, 2009

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.intellgrape.com

  • Share/Bookmark
Posted in Grails