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

Gra*_*her 11 c++ rest basic-authentication casablanca

我正在尝试修改Casablanca教程以包含访问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() );
})

...
Run Code Online (Sandbox Code Playgroud)

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

我一般都是REST和Web的新手,文档也没用 - http_client_config"用于设置可能的配置选项".不开玩笑.我甚至不确定我是否使用了正确的课程 - 这些事情看起来很正常.

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

小智 13

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

// 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();
Run Code Online (Sandbox Code Playgroud)

  • 为什么要在配置中添加凭据*和*还要添加授权标头?一种方式不应该足够吗?至少对我而言,它只需应用其中一个(即通过config.set_credentials). (2认同)