如何在 C++ curl 代码中设置授权持有者 header?我获得的授权不足,尽管它在命令行下有效

How do I set authorization bearer header in C++ curl code? I'm getting insufficient authorization, eventhough it works at the command line

我正在尝试获取使用 curl.h 库的 C++ 代码来发出需要设置授权的 curl 请求:Bearer header。我正在使用 Linux Mint 18 (Ubuntu).

我已经从命令行发出了这个 curl 请求,它有效,它看起来像这样:

curl -H "Content-Type: application/json" -H "Authorization: Bearer <my_token>" <my_url>

这样做 returns 一个有效的结果。

但是,我尝试使用 curl.h 库在 C++ 中编写等效代码,我得到了 {"errorMessage":"Insufficient authorization to perform request."}

这是我使用的 C++ 代码:

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <curl/curl.h>

using namespace std;

int main(int argc, char** argv)
{
    CURL* curl = curl_easy_init();

    if (!curl) {
        cerr << "curl initialization failure" << endl;
        return 1;
    }

    CURLcode res;

    // the actual code has the actual url string in place of <my_url>
    curl_easy_setopt(curl, CURLOPT_URL, <my_url>);

    struct curl_slist* headers = NULL;
    curl_slist_append(headers, "Content-Type: application/json");

    // the actual code has the actual token in place of <my_token>
    curl_slist_append(headers, "Authorization: Bearer <my_token>");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    res = curl_easy_perform(curl);

    if (res != CURLE_OK) {
        cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
    }

    curl_easy_cleanup(curl);

    return 0;
}

我也尝试过使用如下所示的行:

curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, <my_token>);

代替这一行:

curl_slist_append(headers, "Authorization: Bearer <my_token>");

我也曾尝试在 curl_easy_perform:

之前添加这些行
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);

curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

因为我在四处搜索时看到了那些行

但是我为弄清楚如何让这个工作所做的所有努力仍然给我留下 "errorMessage: insufficient authorization to perform request."

而且,是的,顺便说一下,我已经确保 url 和我使用的令牌都是正确的。

我哪里做错了,如何正确地将顶部的命令行代码转换为等效的 C++ 代码。

您需要在每次调用中将 curl_slist_append() 的 return 值分配给 headers

headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Authorization: Bearer <my_token>");

this doc

您调用它的方式 headers 将始终保持为 NULL,这就是您传递给 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

的内容

我遇到了与 CURLOPT_XOAUTH2_BEARER 相同的问题。解决方案是将 CURLOPT_HTTPAUTH 设置为 CURLAUTH_BEARER,如下所示:

curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, "<my_token>");
curl_easy_setopt(_connection, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);

CURLAUTH_BEARER 是在 7.61.0 中添加的。如果您的 libcurl 较旧,CURLAUTH_ANY 应该可以工作。