我正在为我的 Dropwizard
+ Liquibase
+ Angular
应用程序编写集成测试来测试 REST 服务。
我的应用程序使用 cookie 进行基本身份验证。
所以我创建了 ClassRule:
@ClassRule
public static final DropwizardAppRule<RESTServerConfiguration> RULE =
new DropwizardAppRule<>(RESTServer.class, ResourceHelpers.resourceFilePath("serverconfig.yml"));
当我测试登录
方法时:
final Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/login")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json("{\"username\": \"admin\", \"password\": \"admin\"}"));
一切正常。
但是当我尝试测试 protected 资源时,例如:
final TestResponse response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/getAllUsers")
.request()
.get(TestResponse.class);
失败并出现 401 错误。
如何获取 SecurityContext 或将 session 存储在某处?
最佳答案
我终于弄清楚了。
我需要做的就是从登录
请求中提取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(";"));
}
}
`
然后将其设置为 protected 资源请求的 header ,如:
.header("Cookie", cookieValue)
关于java - 获取用于 Dropwizard 集成测试的 SecurityContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47285384/