我正在尝试使用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...)
答案 0 :(得分:3)
中间件'auth:api'自动将请求重定向到登录页面(在这种情况下不存在,因此404错误)。
客户端凭据授权不需要登录。它的文档尚未发布,但中间件does exist。
要使用它,请在$routeMiddleware
中的app\Http\Kernel.php
变量下创建一个新的中间件,如下所示:
protected $routeMiddleware = [
'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
];
然后将此中间件添加到路径的末尾:
Route::get('/hello', function() {
return 'hello';
})->middleware('client_credentials');
这对我有用。