【问题标题】:Route not found after adding 'auth:api' middleware Laravel 5.3添加'auth:api'中间件Laravel 5.3后找不到路由
【发布时间】:2017-02-23 17:06:00
【问题描述】:

我正在尝试使用 laravel 5.3 中的新 oauth2 功能从我的一个 laravel 项目到另一个项目的 api 调用。

我想从旧项目调用的新 laravel 项目的 api.php 路由文件中有这条路由:

Route::get('/hello', function() {
    return 'hello';
})->middleware('auth:api');

如果没有中间件,我可以毫无问题地调用它,使用中间件,它会抛出 404 not found 错误。

这是检索访问令牌然后进行 api 调用的代码:

$http = new GuzzleHttp\Client;

$response = $http->post('http://my-oauth-project.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'client_credentials',
        'client_id' => 'client_id',
        'client_secret' => 'client_secret',
    ],
]);
$token = json_decode($response->getBody(), true)['access_token'];

$response = $http->get('http://my-oauth-project.com/api/hello', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$token,
    ],
]);
return $response->getBody();

返回的错误:

[2016-10-14 09:46:14] local.ERROR: exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `GET http://my-oauth-project.com/api/hello` resulted in a `404 Not Found` response:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="robots" content="noindex,nofollow (truncated...)

【问题讨论】:

    标签: php laravel-5 oauth-2.0


    【解决方案1】:

    中间件 'auth:api' 自动将请求重定向到登录页面(在这种情况下不存在,因此出现 404 错误)。

    客户端凭据授予不需要登录。它的文档尚未发布,但中间件does exist

    要使用它,请在 app\Http\Kernel.php 中的 $routeMiddleware 变量下创建一个新的中间件,如下所示:

    protected $routeMiddleware = [
        'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
    ];
    

    然后将此中间件添加到路由的末尾:

    Route::get('/hello', function() {
        return 'hello';
    })->middleware('client_credentials');
    

    这对我有用。

    【讨论】:

    • 我无法想象文档所说的中间件会因为文档广泛涵盖的内容(客户端凭据和密码授予)而损坏。无论如何,感谢您找到这个!
    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2017-08-10
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多