Laravel Passport 无法使用令牌授权

Can't use token authorization with Laravel Passport

我正在将 Laravel Passport 设置为像 api 一样工作,但即使我通过 oauth/token 获取令牌数据,我似乎也无法将其与 curl 一起使用.

我正在使用 curl 进行连接,因为大多数将要连接的应用程序已经完成,其中许多使用基本 php。

以下代码从我的 laravel 应用程序中获取 token_type 和 access_token。

$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));

但是当我尝试使用令牌数据连接到页面时,我总是收到消息 {"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));

我的 routes/api.php 很基础

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

如果我删除中间件部分,我就可以连接了。那么,我在认证方面做错了什么?

您在带单引号的字符串中使用变量,因此实际变量永远不会被解析。如果要对值进行插值,则应使用双引号。

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