我使用Laravel 5.3和Dingo API,我试图让Laravel的OAuth 2.0(也就是Passport)与Dingo的身份验证一起使用。
我在config/api.php
中添加了OAuth 2.0提供程序,我找到了here:
'auth' => [
'oauth' => function($app) {
$provider = new Dingo\Api\Auth\LeagueOAuth2Provider($app['oauth2.resource-server']);
$provider->setUserCallback(function($id) {
return User::find($id);
});
$provider->setClientCallback(function($id) {
return Client::find($id);
});
return $provider;
}
]
然后我将api.auth
中间件添加到我的路线上:
$api = app('Dingo\Api\Routing\Router');
$api->version('v2', function($api) {
# ...
$api->get('test', ['middleware' => 'api.auth', 'App\Http\Controllers\v2\SnippetController@test']);
});
当请求/api/test
时,我收到500
HTTP响应并出现此错误:
Call to undefined method Closure::authenticate()
可以找到完整的JSON响应(包括跟踪)here
可悲的the docs勉强提到用league/oauth2-server
设置Dingo,这是Laravel使用的
答案 0 :(得分:0)
答案 1 :(得分:0)
我必须使用以下代码在app/Providers/PassportDingoProvider.php
上创建新的提供程序:
<?php
namespace App\Providers;
use Dingo\Api\Routing\Route;
use Illuminate\Http\Request;
use Illuminate\Auth\AuthManager;
use Dingo\Api\Auth\Provider\Authorization;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class PassportDingoProvider extends Authorization
{
/**
* Illuminate authentication manager.
*
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $auth;
/**
* The guard driver name.
*
* @var string
*/
protected $guard = 'api';
/**
* Create a new basic provider instance.
*
* @param \Illuminate\Auth\AuthManager $auth
*/
public function __construct(AuthManager $auth)
{
$this->auth = $auth->guard($this->guard);
}
/**
* Authenticate request with a Illuminate Guard.
*
* @param \Illuminate\Http\Request $request
* @param \Dingo\Api\Routing\Route $route
*
* @return mixed
*/
public function authenticate(Request $request, Route $route)
{
if (! $user = $this->auth->user()) {
throw new UnauthorizedHttpException(
get_class($this),
'Invalid API token'
);
}
return $user;
}
/**
* Get the providers authorization method.
*
* @return string
*/
public function getAuthorizationMethod()
{
return 'Bearer';
}
}
然后我在config/api.php
中添加了这个:
'auth' => [
'custom' => \App\Providers\PassportDingoProvider::class
]
稍后,我可以使用api.auth
中间件来验证我的路线。
您也可以通过Auth::guard('api')->user()
而不是Auth::user()