127

I get my bearer token from an API end point and set the following:

$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

Next, I want to use cURL to access the secure endpoint however I am unsure on how or where to set the Bearer token.

I have tried this but it does not work:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);

According to the documentation, I am supposed to be using the bearer token as such:

GET /oauth/resource HTTP/1.1
Accept: application/json
Authorization: Bearer 907c762e069589c2cd2a229cdae7b8778caa9f07
Ivar
  • 6,138
  • 12
  • 49
  • 61
HappyCoder
  • 5,985
  • 6
  • 42
  • 73

7 Answers7

164

Replace:

$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

with:

$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274";

to make it a valid and working Authorization header.

Hans Z.
  • 50,496
  • 12
  • 102
  • 115
  • Hi - this is something I tried, however with the same problem. I suspect the issue may be something to do with an Apigility update, as I cant get this to work on postman either. – HappyCoder May 25 '15 at 09:34
  • Resolved this by rolling back ApiGility to a previous stable version. Thanks for your input, although not my solution, it is a solution for others with a similar problem and it did get me onto the right track. Thank you for your input! – HappyCoder May 25 '15 at 10:05
63

This is a cURL function that can send or retrieve data. It should work with any PHP app that supports OAuth:

function jwt_request($token, $post) {

    header('Content-Type: application/json'); // Specify the type of data
    $ch = curl_init('https://APPURL.com/api/json.php'); // Initialise cURL
    $post = json_encode($post); // Encode the data array into a JSON string
    $authorization = "Authorization: Bearer ".$token; // Prepare the authorisation token
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Set the posted fields
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
    $result = curl_exec($ch); // Execute the cURL statement
    curl_close($ch); // Close the cURL connection
    return json_decode($result); // Return the received data

}

Use it within one-way or two-way requests:

$token = "080042cad6356ad5dc0a720c18b53b8e53d4c274"; // Get your token from a cookie or database
$post = array('some_trigger'=>'...','some_values'=>'...'); // Array of data with a trigger
$request = jwt_request($token,$post); // Send or retrieve data
xxx
  • 1,153
  • 1
  • 11
  • 23
SergeDirect
  • 2,019
  • 15
  • 20
  • Someone added a negative vote, could you elaborate in the comments below, please. – SergeDirect Apr 11 '18 at 00:16
  • 2
    Thanks Serge... Been struggling for too long with a call like this. *ALL* the docs say "build the POST array with http_build_query ()." BUT that does not work - I don't know if it's an OAuth peculiarity, but what you need is json_encode as you show here. Virtual beer sent. – anoldermark Jun 06 '18 at 16:40
  • 2
    @anoldermark Glad to be helpful. Thanks a lot for the thumb up, makes a real difference. It takes time and effort to write quality answers, upvotes and positive comments are encouraging...to write more, to write good ;) – SergeDirect Jun 08 '18 at 03:51
  • @SergeDirect,How we will get post values in file https://APPURL.com/api/json.php and how work jwt authitication.Please gave an example. – akgola Sep 02 '19 at 08:45
  • @akgola, your question is hard to understand. Please rewrite it, so I can understand how I can help you... For example: How to save results in a variable and then write them into a file. Or How I can extract and use authentication data from a file for the requests. P.S. You must understand I am very limited in what I can answer here, but you can always post a job/Project/Question in Stackoverflow and invite me here by linking to it in comment, then I can help you to solve unrelated issues. You can also ask me question via my GitHub account – SergeDirect Sep 14 '19 at 05:35
  • 1
    Can you help for this? https://stackoverflow.com/questions/58581568/why-authorization-bearer-is-not-sent – user4271704 Oct 27 '19 at 17:33
16

This should works

$token = "YOUR_BEARER_AUTH_TOKEN";
//setup the request, you can also use CURLOPT_URL
$ch = curl_init('API_URL');

// Returns the data/output as a string instead of raw data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Set your auth headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Authorization: Bearer ' . $token
   ));

// get stringified data/output. See CURLOPT_RETURNTRANSFER
$data = curl_exec($ch);

// get info about the request
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
Sudirman Hung
  • 161
  • 1
  • 2
9

As at PHP 7.3:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);
curl_setopt($ch,CURLOPT_XOAUTH2_BEARER,$bearerToken);
Pancho
  • 2,043
  • 24
  • 39
5
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "your api goes here",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer eyJ0eciOiJSUzI1NiJ9.eyJMiIsInNjb3BlcyI6W119.K3lW1STQhMdxfAxn00E4WWFA3uN3iIA"
  ),
 ));

$response = curl_exec($curl);
$data = json_decode($response, true);

echo $data;

?>
Raj Shekhar
  • 109
  • 1
  • 5
4

Guzzle example:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$token = 'your_token';

$httpClient = new Client();

$response = $httpClient->get(
    'https://httpbin.org/bearer',
    [
        RequestOptions::HEADERS => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ]
    ]
);

print_r($response->getBody()->getContents());

See https://github.com/andriichuk/php-curl-cookbook#bearer-auth

1

If you are working with a private token instead (like Gitlab API), you should replace:

$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

with:

$authorization = "PRIVATE-TOKEN 080042cad6356ad5dc0a720c18b53b8e53d4c274";

GuGuss
  • 81
  • 7