我想使用请求映射测试由spring security保护的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。
答案 0 :(得分:2)
如果您只是使用Spring Security Core Plugin
并为受保护的URL(端点)实现传统的有状态链,那么您可以使用Geb
并编写功能测试用例。
但是,如果您使用Spring Security Rest Plugin
并为您的网址实施无状态链,那么您需要首先点击api/login
端点并获取您的访问令牌,然后使用{{1请求中的标头。
您可以找到详细指南here。
我希望这会有所帮助。