HtmlUnit Basic-auth问题

时间:2015-04-20 23:52:06

标签: basic-authentication htmlunit

使用HtmlUnit测试经过身份验证的REST-api似乎很简单。然而,我似乎无法让它发挥作用。

我有以下代码:

@Test
public void testApi() throws IOException {

    WebClient webClient = new WebClient();
    webClient.addRequestHeader("ACCEPT", "application/json");
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

    // Incorrect authentication data
    DefaultCredentialsProvider userCredentials = new DefaultCredentialsProvider();
    userCredentials.addCredentials("someuser", "wrongpass");
    webClient.setCredentialsProvider(userCredentials);

    page = webClient.getPage("http://localhost:8081/apiv/");
    assertEquals(401, page.getWebResponse().getStatusCode());
    userCredentials.clear();

    // Correct authentication data
    userCredentials.addCredentials("someuser", "correctpass");
    webClient.setCredentialsProvider(userCredentials);
    page = webClient.getPage("http://localhost:8081/apiv/");

    assertEquals(200, page.getWebResponse().getStatusCode());
}

使用数据包嗅探器进行检查时,不会发送任何身份验证标头。既不是“不正确的身份验证数据”,也不是“正确的身份验证数据”。

1 个答案:

答案 0 :(得分:0)

由于两个不同的问题,我的测试没有工作:

服务器没有WWW-Authenticate标头。

请注意,无论凭据提供程序集如何,HtmlUnit都会首先发送一个普通请求。只有服务器请求身份验证时,才会发送basic-auth标头。

事实证明我测试的api有一个错误,而不是发送WWW-Authenticate标题。

添加后:

resp.setHeader("WWW-Authenticate", "BASIC realm=\"apiv2\"");

针对“不正确的”'发送了身份验证标头。测试用例。


如何针对每个请求发送身份验证信息?

可在此处找到解决方案:

Passing basic auth credentials with every request with HtmlUnit WebClient

这个答案似乎借鉴于:http://www.drawbackz.gq/stack/386935/passing-basic-auth-credentials-with-every-request-with-htmlunit-webclient.html


CredentialsProvider只能使用一次

根据建议here,CredentialsProvider只能使用一次。之后,它会被标记为“已回答”,并且在后续请求中不会再次发送auth-header。

因此,有必要在每个请求上创建一个带有新CredentialsProvider的新WebClient。以下代码适用于我:

@Test
public void testApi() throws IOException {

    WebClient webClient = new WebClient();
    webClient.addRequestHeader("ACCEPT", "application/json");
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

    // Incorrect authentication data
    DefaultCredentialsProvider userCredentials = new DefaultCredentialsProvider();
    userCredentials.addCredentials("someuser", "wrongpass");
    webClient.setCredentialsProvider(userCredentials);

    page = webClient.getPage("http://localhost:8081/apiv/");
    assertEquals(401, page.getWebResponse().getStatusCode());
    userCredentials.clear();


    // Correct authentication data
    webClient = new WebClient();
    webClient.addRequestHeader("ACCEPT", "application/json");
    userCredentials= new DefaultCredentialsProvider();
    userCredentials.addCredentials("someuser", "correctpass");
    webClient.setCredentialsProvider(userCredentials);
    page = webClient.getPage("http://localhost:8081/apiv/");

    assertEquals(200, page.getWebResponse().getStatusCode());
}