首页 文章

添加'auth:api'中间件后未找到路由 Laravel 5.3

提问于
浏览
4

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

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

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

没有中间件我可以毫无问题地调用它,使用中间件,它会抛出 404 未找到的错误。

这是检索访问令牌然后进行 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...)

1 回答

  • 3

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

    客户端凭据授权不需要登录。它的文档尚未发布,但中间件确实存在

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

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

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

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

    这对我有用。

相关问题