Today I am going to explain Grails springSecurity Session testing. Let us make a controller and action that is mentioned below. Here I have made a controller named as UserController and a check action that will check for user authentication and I have made the domain class as User

import grails.plugins.springsecurity.Secured
@Secured('IS_AUTHENTICATED_FULLY')
class UserController{
def springSecurityService	
def check(){	
User user =springSecurityService.currentUser as User 
}

and now make IntegrationTest class in

grails-app/test/integration

and Import IntegrationSpec, SpringSecurityutils,and RequestContextHolder
Here we have to define all Services that we have used in controller in Setup() and make a feature methods like def ‘test for checking user authentication'() {} here we could use character to define feature methods.

import grails.plugin.spock.IntegrationSpec
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.web.context.request.RequestContextHolder
class UserControllerIntegrationSpec extends IntegrationSpec
{	
User usercontroller	
def springsecurityService
def Setup()	
{	
usercontroller = new UserControllerName()                    	
usercontroller.SpringSecurityService = springsecurityService
}
def "test for checking user authentication"()
{ 
when:   		
springSecurityService.reauthenticate("username")  	                     		
then:
println "***********Hello test passed***********";
}
}

Now try to run the test-case,see what happens in console.Is it “Hello test passed” printed.

java.lang.NullPointerException: Cannot get property 

Now think why, because at the controller it is defined @Secured(‘IS_AUTHENTICATED_FULLY’). So, the user who is logged in and having session provided by spring Security could access the controller,otherwise no. And if you will see in the above code you will find that I have not provided any session to user. Now change the code and add one more line in when field and run again.

RequestContextHolder.currentRequestAttributes().session.User

You will see that test got passed by printing.

***********Hello test passed***********

Here main thing is that if user is logged in than user is provided a session till user does not close his application and it is maintained by SpringSecurity plug-in.

By this process we could test the user session and user authentication