如何在集成测试中与其余客户端共享 spring 安全性 session

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

我想使用请求映射测试由 spring 安全保护的 rest API。 API 主要由经过身份验证的用户使用,因此我想用登录用户测试 API。

在我使用的其余客户端的测试中

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

在调用 API 之前,必须对用户进行身份验证。我在设置中尝试了以下操作:

    springSecurityService.reauthenticate "admin"

尽管重新验证调用没有 session 其余客户端可以检测到,因此状态代码为 302 -> 重定向到登录页面。

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
}

session如何与其他客户端共享?正如您在注释行中看到的那样,一种想法是在请求 header 中添加 session ID,但如何在集成测试中请求 session ID。

如果您只是使用 Spring Security Core Plugin 并为受保护的 URL(端点)实施传统的有状态链,那么您可以使用 Geb 并编写功能测试用例。

但是,如果您正在使用 Spring Security Rest Plugin 并为您的 URL 实施无状态链,那么您需要先点击 api/login 端点并获取您的访问令牌,然后使用 Authorization header 在请求中。

您可以找到详细的指南 here

希望对您有所帮助。