首页 > 解决方案 > Libcurl 身份验证问题

问题描述

我正在尝试在 C++ 中使用 libcurl 将请求发送到 url。当我使用 curl 在命令行中设置请求时,它似乎工作正常:

curl -vvv -X POST -H "Authorization: <api key here>" -H "Content-Type:application/json" "<host>" --data-binary '<json data here>'

响应开始如下:

> POST <host> HTTP/1.1
> Host: <host>
> User-Agent: curl/7.61.1
> Accept: */*
> Authorization: <api_key>
> Content-Type:application/json
> Content-Length: 80

所以我可以看到授权正在正确发送。

但是,当我尝试使用 libcurl C 库在 C++ 中做类似的事情时,我没有注意到请求标头前面的“>”:

代码:

    struct curl_slist *chunk = NULL;
    chunk = curl_slist_append(chunk, "Authorization: <api_key>");
    chunk = curl_slist_append(chunk, "Content-Type:application/json");


    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(curl, CURLOPT_URL, "<host>");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "<json>");
    res =  curl_easy_perform(curl);
    curl_easy_cleanup(curl);

回复:

> POST <host> HTTP/1.1
Host: <host>
Accept: */*
Authentication: <api_key>
Content-Type:application/json
Content-Length: 97

所以我什至不确定主机是否正确处理或接收了标头。

有任何想法吗?

我得到以下回复:

{
  "message": "No authorization header given",
  "code": 401
}

标签: c++authenticationcurlheaderlibcurl

解决方案


在您的命令行详细输出中,标题名为“授权:”。在您的 libcurl vebose 输出中,它的“身份验证:”。授权!=身份验证?

详细输出:

它只是命令行和 libcurl 之间的详细输出格式不同。标头已发送。例如 php curl 使用相同的输出格式。只有第一行有“>”,然后所有后面的标题都没有“>”。但是他们都提交了。

PHP curl 详细示例输出:

*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 80 (#0)
> GET /XXX/api.php HTTP/1.1
Host: localhost
Accept: */*
Authorization: XXX
Content-Type: application/json

< HTTP/1.1 200 OK
< Date: Mon, 31 Dec 2018 20:12:51 GMT
< Server: Apache/2.4.34 (Win32) OpenSSL/1.1.0i PHP/7.2.10
< X-Powered-By: PHP/7.2.10
< Content-Length: 2390
< Content-Type: text/html; charset=UTF-8
< 
* Connection #0 to host localhost left intact

推荐阅读