使用 POCO 的客户端摘要式身份验证

Client Digest Authentication with POCO

我正在为某些服务客户端使用 POCO。客户端应使用摘要身份验证登录。

POCO documentation claims that digest authentication is supported.

This is a utility class for working with HTTP authentication (basic or digest) in HTTPRequest objects.

这是测试 (gtest) 的完整源代码,显示存在一些问题:

#include "UnitTest.h"
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/StreamCopier.h>
#include <Poco/Net/HTTPCredentials.h>

using namespace Poco::Net;

TEST(PocoDigestAuthTest, HttpBibOrgTest) {
    HTTPClientSession session;
    session.setHost("httpbin.org");

    HTTPRequest request(
        "GET", 
        // "http://httpbin.org/basic-auth/user/passwd", // basic
        "http://httpbin.org/digest-auth/auth/user/passwd",  // digest
        HTTPMessage::HTTP_1_1);
    session.sendRequest(request);

    HTTPResponse response;
    std::istream& firstResponseStream = session.receiveResponse(response);
    std::stringstream firstStrStream;
    Poco::StreamCopier::copyStream(firstResponseStream, firstStrStream);

    ASSERT_EQ(HTTPResponse::HTTP_UNAUTHORIZED, response.getStatus());

    HTTPCredentials creds("user", "passwd");
    creds.authenticate(request, response);
    session.sendRequest(request);

    std::istream& bodyStream = session.receiveResponse(response);
    EXPECT_NE(HTTPResponse::HTTP_UNAUTHORIZED, response.getStatus());
    EXPECT_EQ(HTTPResponse::HTTP_OK, response.getStatus());

    std::stringstream strStream;
    Poco::StreamCopier::copyStream(bodyStream, strStream);
    EXPECT_NE("", strStream.str());
}

此测试在预期状态 HTTP_OK 处失败,我收到 401 (HTTP_UNAUTHORIZED),因此之前的检查也失败了。

如果我将 uri 更改为具有基本身份验证的站点,一切都会按预期运行(测试通过)。

我做错了什么?或者它是 POCO 中的错误?我能以某种方式修复它吗?

经过一些测试和思考后发现问题与摘要身份验证无关。您还需要发送 httpbin.org 服务器设置的 cookie (fake=fake_value)。 Here 是您的样本的修改版本。请注意对 setCookies() 的额外调用。此外,在创建 HTTPRequest 时,只需要提供路径,而不是整个 URI。