Testing spring security (formerly acegi) in your controllers.

dave

Administrator
Staff member
It appears there has been a few people asking how to do this..

With the update to the 'acegi' plugin, 'spring-security-core' it's very straightforward..

In your controller test class, you will need to inject the securityservice, formerly this was the authenticationService so add a

def springSecurityService

into your class.

In your setup we will create an instance of the controller you want to test and pass into it the security service then authenticate a user by username.

Also ensure in the tearDown() stub you clear the security context.

So setup and tearDown will methods would be something like...
Code:
void setUp() {
      super.setUp()
      controller = new ClientController(
         springSecurityService:springSecurityService)
  }

protected void tearDown() {
        super.tearDown()
        SecurityContextHolder.clearContext()
    }

Then you can pretty much assume your controller logic should be picking up your logged in user.. My code in this case is...
Code:
def principal = springSecurityService.principal
def user = User.get(principal.id)
 
Top