Search code examples
grailsspring-securitygrails-plugin

How to share spring security session with rest client in integration test


I wanna test a rest API secured by spring security using request maps. The API is mainly used by authenticated users, therefore I wanna test the API with logged in user.

In the test for the rest client I use

    testCompile "org.grails:grails-datastore-rest-client:6.0.5.RELEASE"

Before calling the API the user must be authenticated. I tried following within the setup:

    springSecurityService.reauthenticate "admin"

Despite the reauthenticate call there is no session the rest client could detect, therefore the status code is 302 -> redirect to login page.

void "test fetching execution statistic"() {
    given:
    RestBuilder rest = new RestBuilder()
    when:
    //requestHeaders.add("Cookie", "JSESSIONID=" + session.getValue());

    RestResponse response = rest.post("http://localhost:8080/correctionStatistic/executionStatistic") {
        json([
                reportingPeriod_year: 2008,
                reportingPeriod_month: 01
        ])
    }
    then:
    response.status == 200
}

How can the session be shared with the rest client? As you can see in the commented line, one idea would be to add the session ID in the request header, but how to request the session ID in the integration test.


Solution

  • If you are just using Spring Security Core Plugin and implementing the traditional stateful chain for the protected URLs(endpoints), then you can use Geb and write functional test cases.

    But if you are using the Spring Security Rest Plugin and implementing a stateless chain for your URLs, then you need to first hit the api/login endpoint and get your access token and then make futher requests with Authorization header in the requests.

    You can find the detailed guide here.

    I hope this helps.