【发布时间】:2013-03-01 18:05:22
【问题描述】:
我正在尝试使用 Wink RestClient 对 Rest 服务端点进行功能测试。我使用模拟进行单元测试,但我想在功能上测试它作为端点消费者。
我知道有些人会反对我在使用基于表单的身份验证时将其称为 REST 端点,但这是我目前的架构。
我要测试的大部分资源都是受保护的资源,并且应用程序(在 Tomcat6 上运行)受表单身份验证的保护。 (如在下面的 web.xml sn-p 中)。
到目前为止,我尝试的是对未受保护的资源进行初始调用,以获取包含 JSESSIONID 的 set-cookie 标头,并在随后的标头中使用该 JSESSIONID(通过 Resource.cookie() )请求,但没有结果。
web.xml
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/login.html?failure=true</form-error-page>
</form-login-config>
</login-config>
我的 Wink RestClient 代码如下所示。所有响应都是 200,但我注意到两件事是对 /j_security_check/ 的调用的响应不包括 jsessionid cookie,对受保护资源的调用说我登录失败。调用 j_security_check 的负载是直接从之前拦截的成功浏览器请求中捕获的。
ClientConfig config = new ClientConfig();
config.setBypassHostnameVerification(true);
RestClient restClient = new RestClient(config);
Resource unprotectedResource = restClient.resource( BASE_URL + "/");
unprotectedResource.header( "Accept", "*/*" );
ClientResponse clientResponse = unprotectedResource.get();
String response = clientResponse.getEntity(String.class);
// get jSession ID
String jSessionId = clientResponse.getHeaders().get("set-cookie").get(0);
jSessionId = jSessionId.split(";")[0];
System.out.println(jSessionId);
// create a request to login via j_security_check
Resource loginResource = restClient.resource(BASE_URL + "/j_security_check/");
loginResource.accept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
loginResource.header("referer", "http://localhost:8080/contextroot/");
loginResource.cookie( jSessionId );
loginResource.header("Connection", "keep-alive");
loginResource.header("Content-Type", "application/x-www-form-urlencoded");
loginResource.header("Content-Length", "41");
ClientResponse loginResponse = loginResource.post("j_username=*****&j_password=*************");
/* the loginResponse, as this point, does not have the jsessionid cookie, my browser client does */
Resource protectedResource = restClient.resource(BASE_URL + "/protected/test/");
systemResource.accept("application/json");
systemResource.cookie( jSessionId );
ClientResponse systemResponse = systemResource.get();
response = clientResponse.getEntity(String.class);
System.out.println(response);
如果您有任何使用 Wink RestClient 来使用受表单身份验证保护的资源的想法或经验,我们将不胜感激。我想我会接受其他框架,我听说过 REST-Assured 和其他框架,但是由于应用程序使用 Wink 并且 RestClient 似乎为我提供了我需要的东西,所以我想我会坚持下去。
【问题讨论】:
-
原来 j_security_check 以 [#302 临时移动] 响应 - 当我使用嗅探器拦截请求并将 JSESSIONID cookie 附加到该重定向请求时,一切都很好。问题是我似乎无法从 wink RestClient 对象(或资源或响应)对象中得到。重定向发生在幕后。任何人都知道如何指示 Resource.post() 方法停止重定向,或指示 ClientResponse 捕获重定向?我还看不到方法。
标签: rest jax-rs junit4 functional-testing apache-wink