Correct way to set Bearer token with cURL

Correct way to set Bearer token with cURL

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Missing Authorization Header in cURL Requests

When constructing a cURL request to access a protected API endpoint, the most common point of failure is how the Authorization header is formatted and attached to the session handle. You have successfully retrieved your bearer token from an API endpoint, likely something like 080042cad6356ad5dc0a720c18b53b8e53d4c274. The goal is straightforward: send a request that the server accepts as authenticated.

The issue in your current implementation lies in how CURLOPT_HTTPHEADER handles multiple headers. You are correctly identifying that the header must look like Authorization: Bearer <token>, matching the format shown in standard HTTP specifications and OAuth 2.0 documentation. However, simply concatenating this string into an array passed to curl_setopt requires careful attention to syntax and order.

In your code snippet, you are passing two distinct headers:

  1. Content-Type: application/json
  2. $authorization (which contains Bearer <token>)

The logic here is sound, but the variable construction needs verification. If $authorization holds the string "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274", then passing it directly into CURLOPT_HTTPHEADER should work, provided there are no trailing whitespace characters or newline artifacts (\n) appended to the string. These invisible characters often cause servers to reject the token because they break the expected line structure of HTTP headers.

Here is the corrected approach for setting up the cURL handle:

$token = '080042cad6356ad5dc0a720c18b53b8e53d4c274';
$url = 'https://api.example.com/secure-endpoint';

$ch = curl_init($url);

// Define headers as an array of "Key: Value" strings
$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $token
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true); // Preferred over CUSTOMREQUEST for POST
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post)); // Ensure JSON is encoded
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($result === false) {
    throw new Exception('cURL error: ' . curl_error($ch));
}

// Always check the HTTP code to ensure authentication actually worked
if ($httpCode >= 400) {
    // Handle potential 401 Unauthorized or 403 Forbidden errors here
} else {
    return json_decode($result);
}

curl_close($ch);

The primary distinction between your working example and the non-working one usually boils down to two factors: variable concatenation safety and error handling. When you manually concatenate the token into the $authorization string, ensure no extra spaces are added. A trailing space turns Bearer abc123 into Bearer abc123 , which many strict OAuth gateways will reject immediately with a 401 Unauthorized response.

Furthermore, relying solely on curl_exec() returning JSON is insufficient for production code. You must inspect the HTTP status code returned by cURL. Even if the response body contains data, a 401 or 403 status code indicates that the token was rejected. The documentation from Apigility emphasizes that the Authorization header is the gatekeeper; without it formatted exactly as Bearer <token>, the server ignores the request body entirely.

Another consideration involves the Content-Type. While your original code sets this correctly, ensure that $post is actually valid JSON. Passing raw strings to CURLOPT_POSTFIELDS can lead to serialization errors if the API expects a structured payload. Using json_encode() explicitly prevents ambiguity about whether the server receives a string or an object.

If you are working within the Laravel ecosystem and dealing with OAuth 2.0 tokens, you might find that using the framework's HTTP client (Http::withToken()) is more robust than raw cURL commands. This approach handles token expiration and refresh logic automatically. However, if raw cURL is required for your specific integration, strict adherence to the header format Authorization: Bearer <token> remains mandatory.

Finally, remember that bearer tokens are sensitive credentials. Storing them in variables passed directly to scripts or logging them in error output poses a security risk. Always sanitize responses before logging and ensure your .env files restrict access to the logic that generates or holds these tokens.

Our network