简体   繁体   English

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

[英]Route not found after adding 'auth:api' middleware Laravel 5.3

I'm trying to do an api call from one of my laravel projects to another using the new oauth2 feature in laravel 5.3. 我正在尝试使用laravel 5.3中的新oauth2功能从我的一个laravel项目中进行到另一个的api调用。

I have this route in the api.php route file of my new laravel project that I want to call from the old one: 我的新laravel项目的api.php路由文件中有此路由,我想从旧的调用此文件:

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

Without the middleware I can call it without a problem, with the middleware, it throws a 404 not found error. 没有中间件,我可以毫无问题地调用它,使用中间件,它会引发404 not found错误。

Here is the code that retrieves the access token and then makes the api call: 这是获取访问令牌然后进行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();

The error that is returned: 返回的错误:

[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...)

The middleware 'auth:api' automatically redirects the request to a login page (which in this case doesn't exist, hence the 404 error). 中间件“ auth:api”自动将请求重定向到登录页面(在这种情况下不存在,因此出现404错误)。

The client credentials grant doesn't require a login. 客户端凭据授予不需要登录。 The documentation for it hasn't been published yet but the middleware does exist . 它的文档还没有发布,但是中间件确实存在

To use it create a new middleware under the $routeMiddleware variable in app\\Http\\Kernel.php like so: 要使用它,请在app\\Http\\Kernel.php$routeMiddleware变量下创建一个新的中间件,如下所示:

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

Then add this middleware onto the end of the route: 然后将此中间件添加到路由的末尾:

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

This is what worked for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM