1

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?

htshame
  • 6,599
  • 5
  • 36
  • 56

1 Answers1

1

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)

htshame
  • 6,599
  • 5
  • 36
  • 56
  • You don't need to do all that. You can use `.cookie(entry.getValue().toCookie())`. And why even loop? Just do a map.get and check for a null. or if you just want to send all the cookies, something like https://stackoverflow.com/a/46878059/2587435 – Paul Samsotha Nov 16 '17 at 15:11
  • @peeskillet You're right, thanks for the comment. The loop is useless indeed. – htshame Nov 17 '17 at 07:25