12

I'm trying to modify the Casablanca tutorial to include basic HTTP authentication to access the Prosper API:

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() );
})

...

Unfortunately, I keep getting error 401 - unauthorized. However, I can access the page in the browser via https://username:password@api.prosper.com/api/Listings/, and I can use Casablanca to get to regular web pages that don't need authentication.

I'm new to REST and web stuff in general, and the documentation is useless - http_client_config is "used to set the possible configuration options." No kidding. I'm not even sure if I'm using the right classes - these things just kind of looked right.

How do I add basic authentication to an http_client request in Casablanca?

GraphicsMuncher
  • 4,269
  • 3
  • 30
  • 48

1 Answers1

15

You need to add a header to your request which contains base64 of your "username:password" for example

// 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();
GraphicsMuncher
  • 4,269
  • 3
  • 30
  • 48
  • 1
    You're a wizard. I used Casablanca's conversions::to_base64("username:password") to convert the string. – GraphicsMuncher Jul 31 '15 at 23:50
  • 4
    Why are you adding the credentials in the configuration *and* also adding the authorization header? Shouldn't one way be sufficient? At least for me, it worked by just applying one of these (i.e. via config.set_credentials). – Mathias Conradt Oct 14 '16 at 09:09