java - 获取用于 Dropwizard 集成测试的 SecurityContext

标签 java angular session liquibase dropwizard

我正在为我的 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/

相关文章:

Java - 确定操作系统位版本

java - 如何使用 lombok 制作私有(private) builder() 方法

javascript - 如何重启间隔?

php - 加载页面时 session 的未定义索引错误

java - 如何检索 tomcat 实例中的 Activity session ?

facebook - 在我的网络应用程序中,当用户从我的网络应用程序注销时,Facebook 帐户会自动断开连接

java - 使用 Java 8 Parallel Stream 在并行读取多个文件时排除一些文件

ilasm/ildasm 的 Java 字节码等价物

angular - Angular 2中,通过ComponentFactory创建Component好像渲染不完全

angular - 如何修复无法读取未定义的属性 'next'?