Search code examples
phplaravelcurllaravel-passport

Can't use token authorization with Laravel Passport


I'm setting up Laravel Passport to work like as an api, but even though I get token data through oauth/token I can't seem to use it with curl.

I'm using curl to connect because most of the applications that will be connecting have already been made and many of them use basic php.

The following code gets me a token_type and an access_token from my laravel app.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:8000/oauth/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ("X-Requested-With: XMLHttpRequest"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$postData = array(
    'client_id' => '6',
    'client_secret' => 'Cprp9HPTYO7CsZRvv4A8MizNj9h1nLjyF6J1sElZ',
    'grant_type' => 'client_credentials',
    'scope' => '*'
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$ans = json_decode(curl_exec($ch));

But when I try to use the token data to connect to a page, I always get back the message {"message":"Unauthenticated."}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:8000/api/test");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Requested-With: XMLHttpRequest',
    'Accept: application/json',
    'Authorization: {$ans->token_type} {$ans->access_token}',
    ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

print_r( curl_exec($ch));

My routes/api.php is pretty basic

Route::get('/test', function() {
    return "Yes! We're testing!!";
})->middleware('client');

and if I remove the middleware part I can connect. So, what am I doing wrong on the authentification?


Solution

  • You're using variables inside a string with single quotes so the actual variables are never parsed. You should use double quotes if you want the value to be interpolated.

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'X-Requested-With: XMLHttpRequest',
        'Accept: application/json',
        "Authorization: {$ans->token_type} {$ans->access_token}",
    ));