I have a working libsoup client which sends data with a HTTP POST and Basic Authentication. The authentication is handled within libsoup
through a callback - when the server requires authentication libsoup
signals it with the callback - and then the function soup_auth_authenticate()
gets passed a given object of type SoupAuth together with the username and password.
#include <iostream>
#include <iomanip>
#include <string>
#include <libsoup/soup.h>
using namespace std;
void authenticate(SoupSession *session, SoupMessage *msg, SoupAuth *auth, gboolean retrying, gpointer data) {
soup_auth_authenticate(auth, "foo", "bar");
}
int main() {
SoupSession* session = soup_session_new_with_options(SOUP_SESSION_USER_AGENT, "stackoverflow",
SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_COOKIE_JAR,
NULL);
g_signal_connect(session, "authenticate", G_CALLBACK(authenticate), nullptr);
SoupMessage* post_msg = soup_message_new("POST", "https://example.org/work.php");
string formdata = "first_name=Captain&last_name=Picard";
soup_message_set_request(post_msg, "application/x-www-form-urlencoded", SOUP_MEMORY_COPY, formdata.c_str(), formdata.size());
soup_session_send_message(session, post_msg);
cout << left << setw(22) << "status code: " << right << post_msg->status_code << "\n";
cout << left << setw(22) << "reason phrase: " << right << post_msg->reason_phrase << "\n";
cout << left << setw(22) << "response body length: " << right << post_msg->response_body->length << "\n";
cout << left << setw(22) << "response body data: " << right << post_msg->response_body->data << "\n";
// TODO call soup_session_send_message() again with modified username and password
return EXIT_SUCCESS;
}
You can compile this with g++ -o sample sample.cpp -Wall -pedantic -g `pkg-config libsoup-2.4 --cflags --libs`
. When you need to test this, please change the domain from example.org
to flapflap.eu
which will give you a working endpoint.
What should I do when I want to send a different username or password in a subsequent call? The library will not use the callback anymore because the authentication is set up and working already.
Do I need create a new SoupSession
? Or can I access the current SoupAuth
and call soup_auth_authenicate()
directly? I want to keep the client working fast.
Thank you for your help
The background information at bottom indicates that you do not need to create a new
SoupSession
to make subsequent authentication requests. It is not clear though that thesoup_auth_authenticate()
call is the method to do that. Following is the list of authentication related calls from this libsoup page:Reading between the lines in this Basics page seems to suggest it is possible to make multiple authentication requests in a single
SoupSession
.This Manpagez post also discusses more than one call to authenticate per session: