Lion King
Lion King

Reputation: 33823

How to send access token to a server API using libCurl

I have registered in a pictures site and I want to use its API to pull some pictures from there.
I have quoted the following from their documentation "To get access you have to add an HTTP Authorization header to each of your requests ".

Currently, I have the API_KEY but I must send it through HTTP Authorization header, I found something similar to my request as follow:

curl -H "Authorization: OAuth " http://www.example.com

The previous command is used in the CURL command prompt but I want the same thing by using libCurl.

Also, I have known an option to set the authorization type but I still don't know how to send the ACCESS_TOKEN:

curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

--

CURL *curl;
CURLcode codeRet;
std::string data;
std::string fullURL = url + keyword;
curl = curl_easy_init();
if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, fullURL.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60L);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
    curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
    codeRet = curl_easy_perform(curl);
    if (codeRet != CURLE_OK)
        // OutputDebugString(wxString(curl_easy_strerror(codeRet)));
        return "";
    curl_easy_cleanup(curl);
}

How to send access token to a server API using libCurl?

Upvotes: 2

Views: 4290

Answers (1)

miradham
miradham

Reputation: 2355

Everything that works with -H option from curl command prompt you can transfer to code using CURLOPT_HTTPHEADER. So I would recommend to make sure that it everything works as you expect from command prompt before moving to libcurl.

In case of access token, you can use access_token keyword, i.e.

curl -H "access_token: abcdefghijklmnopqrstuvwxyz" http://example.com

or

CURL *curl = curl_easy_init();     
struct curl_slist *headers= NULL;
string token = "abcdefghijklmnopqrstuvwxyz"; // your actual token

if(curl) {
  ...
  curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
  string token_header = "access_token: " + token; // access_token is keyword    
  headers = curl_slist_append(headers, token_header.c_tr());     
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  ...

  curl_slist_free_all(headers);
}

This will issue http request to http://example.com?access_token=abcdefghijklmnopqrstuvwxyz link

Upvotes: 1

Related Questions