How to make the libcurl send digest authentication

2019-08-08 02:49发布

问题:

I have the following function http_send_message() wich I use each time I want to send a http message:

http_send_message(char *msg_out, char **msg_in)
{
    CURLcode res;
    CURL *curl;

    curl = curl_easy_init();
    if (!curl) return -1;

    curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.1.133:8080/tawtaw");
    curl_easy_setopt(curl, CURLOPT_USERNAME, "tawtaw");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "tawtaw");
    curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST);
        .
        .
        .
   curl_easy_cleanup(curl); 
}

But I remarked in each time the function send the http message, it try to send a request without the digest authentication header and then it send it with the digest authentication header. In normal case It should do this behaviour only in the first message. And for the subsequent messages it should remeber the authentication header and send it in each message

回答1:

To obtain such a behavior you need to re-use you curl handle for the subsequent calls to take full advantage of persistent connections and Digest Access Authentication request counter:

[...] the client may make another request, reusing the server nonce value (the server only issues a new nonce for each "401" response) but providing a new client nonce (cnonce). For subsequent requests, the hexadecimal request counter (nc) must be greater than the last value it used

In practice do not clean up your curl handle. Instead maintain it and as soon as you need to perform another request:

  • reset it with the curl_easy_reset function: curl_easy_reset(curl);
  • then re-set your options.

If you use the CURLOPT_VERBOSE option you will see that for the subsequent requests you will have an Authorization header with an increasing request counter (nc=00000002, nc=00000003, etc).



标签: c libcurl