2017-11-14 10 views
1

Dropwizardアプリケーションの統合テストを作成して、RESTサービスをテストしています。 私のアプリは、クッキーとの基本認証を持っています。Dropwizard統合テストのSecurityContextを取得

だから私は作成した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を取得したり、セッションをどこに保存したりできますか?

答えて

1

私はついにこのことを考え出しました。 、

`

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

`

、その後、保護されたリソース要求へのヘッダーとして設定:

私が行うために必要なすべては、次のような、login要求からクッキーを抽出することです

.header( "Cookie"、cookieValue)

+0

あなたはすべてをする必要はありません。 '.cookie(entry.getValue()。toCookie())'を使うことができます。そしてなぜループするのだろう? map.getを実行してnullを確認してください。または単にクッキーをすべて送信したい場合は、https://stackoverflow.com/a/46878059/2587435 –

+0

@peeskilletのようにしてください。コメントをいただきありがとうございます。ループは本当に役に立たない。 – htshame