c++ - 在 Casablanca 中设置基本 HTTP 身份验证

标签 c++ rest basic-authentication casablanca

我正在尝试修改 Casablanca tutorial包括访问 Prosper API 的基本 HTTP 身份验证:

auto fileStream = std::make_shared<ostream>();

// Open stream to output file.
auto requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
    *fileStream = outFile;

    // Create http_client to send the request.
    http_client_config config;
    credentials creds( "username", "password" );
    config.set_credentials( creds );
    http_client client( U( "https://api.prosper.com/" ), config );

    // Build request URI and start the request.
    uri_builder builder(U("/api/Listings/"));

    return client.request( methods::GET, builder.to_string() );
})

...

不幸的是,我不断收到错误 401 - 未经授权。但是,我可以通过 https://username:password@api.prosper.com/api/Listings/ 访问浏览器中的页面,并且我可以使用 Casablanca 访问常规网页'需要身份验证。

一般来说,我对 REST 和 Web 内容不熟悉,文档毫无用处 - http_client_config 是“用于设置可能的配置选项”。别开玩笑了。我什至不确定我是否使用了正确的类 - 这些东西看起来有点正确。

如何在 Casablanca 中向 http_client 请求添加基本身份验证?

最佳答案

您需要在您的请求中添加一个 header ,其中包含您的 "username:password"base64 例如

// Please check how to convert into base64

XYZtaW46Wr6yZW0xMAXY = base64("username:password")

// Creating http_client
http_client_config config;
credentials cred(L"username", L"Password");
config.set_credentials(cred);
http_client client(U("https://serverip"),config);
// create header
http_request req(methods::GET);
// Add base64 result to header
req.headers().add(L"Authorization", L"Basic XYZtaW46Wr6yZW0xMAXY");
req.set_request_uri(L"/api/json/xyz");
pplx::task<http_response> responses = client.request(req);
pplx::task<web::json::value> jvalue = responses.get().extract_json();
wcout << jvalue.get().to_string();

关于c++ - 在 Casablanca 中设置基本 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31371659/

相关文章:

c++ - 来自 API 的错误代码......处理的最佳做法是什么

java - Spring Rest 模板覆盖 Authorization header 值

java - 如何从 REST Web 服务读取规范

json - 如何在 iOS9 上做 http 基本认证?

c++ - 显示环境变量 LD_LIBRARY_PATH

c++ - 当 InProcServer32 键定义 DLL 的完整路径时,为什么 PATH 环境变量中需要 COM DLL 的路径?

java - Spring Security HTTP 基本认证

SvelteKit:如何使用 www-authenticate header 保护页面

c++ - 在不区分大小写的文件系统上模拟区分大小写

java - Jersey 2.8,灰熊,SSE : what jar files do i have to download