【问题标题】:Can't use token authorization with Laravel Passport无法通过 Laravel Passport 使用令牌授权
【发布时间】:2017-10-19 23:15:09
【问题描述】:

我正在将 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');

如果我删除中间件部分,我可以连接。那么,我在身份验证上做错了什么?

【问题讨论】:

    标签: php laravel curl laravel-passport


    【解决方案1】:

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

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

    【讨论】:

    • 对不起,我要羞愧地低下头了。
    猜你喜欢
    • 2021-03-14
    • 2017-01-10
    • 2014-06-30
    • 2017-08-22
    • 2021-08-29
    • 2018-02-01
    • 2013-04-11
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多