我想使用请求映射测试由 spring 安全性保护的 rest API。该 API 主要由经过身份验证的用户使用,因此我想用登录用户测试 API。
在我使用的其余客户端的测试中
testCompile "org.grails:grails-datastore-rest-client:6.0.5.RELEASE"
在调用 API 之前,必须对用户进行身份验证。我尝试在设置中执行以下操作:
springSecurityService.reauthenticate "admin"
尽管进行了重新身份验证调用,但其余客户端无法检测到会话,因此状态代码为 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
}
如何与其余客户端共享会话?正如您在注释行中看到的那样,一个想法是在请求标头中添加会话 ID,但不知道如何在集成测试中请求会话 ID。
如果您只是使用 Spring Security Core Plugin
并为受保护的 URL(端点)实现传统的有状态链,那么您可以使用Geb
并编写功能测试用例。
但是,如果您正在使用Spring Security Rest Plugin
并为 URL 实现无状态链,则需要首先点击 api/login
终结点并获取访问令牌,然后在请求中使用 Authorization
标头发出进一步的请求。
您可以在此处找到详细指南。
我希望这有所帮助。