为 Dropwizard 集成测试获取 SecurityContext
Get SecurityContext for Dropwizard integration tests
我正在为我的 Dropwizard
+ Liquibase
+ Angular
应用程序编写集成测试以测试 REST 服务。
我的应用程序使用 cookie 进行基本身份验证。
所以我创建了 ClassRule:
@ClassRule
public static final DropwizardAppRule<RESTServerConfiguration> RULE =
new DropwizardAppRule<>(RESTServer.class, ResourceHelpers.resourceFilePath("serverconfig.yml"));
当我测试 login
方法时:
final Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/login")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json("{\"username\": \"admin\", \"password\": \"admin\"}"));
一切正常。
但是当我尝试测试受保护的资源时,例如:
final TestResponse response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/getAllUsers")
.request()
.get(TestResponse.class);
失败并出现 401 错误。
如何获取 SecurityContext 或将会话存储在某处?
我终于想通了。
我需要做的就是从 login
请求中提取 cookie,例如:
`
String cookieValue = null;
for (Map.Entry<String, NewCookie> entry : loginResponse.getCookies().entrySet()) {
String key = entry.getKey();
if ("sessionToken".equals(key)) {
cookieValue = entry.getValue().toString();
cookieValue = cookieValue.substring(0, cookieValue.indexOf(";"));
}
}
`
然后设置为受保护资源请求的header,如:
.header("Cookie", cookieValue)
我正在为我的 Dropwizard
+ Liquibase
+ Angular
应用程序编写集成测试以测试 REST 服务。
我的应用程序使用 cookie 进行基本身份验证。
所以我创建了 ClassRule:
@ClassRule
public static final DropwizardAppRule<RESTServerConfiguration> RULE =
new DropwizardAppRule<>(RESTServer.class, ResourceHelpers.resourceFilePath("serverconfig.yml"));
当我测试 login
方法时:
final Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/login")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json("{\"username\": \"admin\", \"password\": \"admin\"}"));
一切正常。
但是当我尝试测试受保护的资源时,例如:
final TestResponse response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/getAllUsers")
.request()
.get(TestResponse.class);
失败并出现 401 错误。
如何获取 SecurityContext 或将会话存储在某处?
我终于想通了。
我需要做的就是从 login
请求中提取 cookie,例如:
`
String cookieValue = null;
for (Map.Entry<String, NewCookie> entry : loginResponse.getCookies().entrySet()) {
String key = entry.getKey();
if ("sessionToken".equals(key)) {
cookieValue = entry.getValue().toString();
cookieValue = cookieValue.substring(0, cookieValue.indexOf(";"));
}
}
`
然后设置为受保护资源请求的header,如:
.header("Cookie", cookieValue)