Search code examples
javaangularsessionliquibasedropwizard

Get SecurityContext for Dropwizard integration tests


I'm writing integration tests for my Dropwizard + Liquibase + Angular application to test the REST service. My app has basic authentication with cookies.

So I've created ClassRule:

@ClassRule
public static final DropwizardAppRule<RESTServerConfiguration> RULE =
            new DropwizardAppRule<>(RESTServer.class, ResourceHelpers.resourceFilePath("serverconfig.yml"));

When I test the login method:

final Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/login")
    .request(MediaType.APPLICATION_JSON)
    .post(Entity.json("{\"username\": \"admin\", \"password\": \"admin\"}"));

everything works fine.

But when I try to test the protected resource, e.g.:

final TestResponse response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/getAllUsers")
    .request()
    .get(TestResponse.class);

it fails with 401 error.

How can I get SecurityContext or store the session somewhere?


Solution

  • I finally figured this thing out.

    All I needed to do is to extract cookies from login request, such as:

    `

    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(";"));
        }
    }
    

    `

    and then set it as a header to the protected resource request, such as:

    .header("Cookie", cookieValue)