1.根据作用域生成token
$user->createToken($request->name,['test1'])->accessToken;
2.注册中间件
'scopes' => \App\Http\Middleware\CheckScopes::class, 'scope' => \App\Http\Middleware\CheckForAnyScope::class
3.添加指定路由的中间件
->middleware(['scope:test1,test2']);
4.passport提供的中间件很好的完成了限制的功能 当没有指定的作用域的时候会抛出异常 不太友好 所以重写了两个中间件 做出相应的解决办法
class CheckForAnyScope extends \Laravel\Passport\Http\Middleware\CheckForAnyScope { public function handle($request, $next, ...$scopes){ try{ $request = parent::handle($request, $next, ...$scopes); return $request; }catch(MissingScopeException $e){ Log::info(['error' => $e->getMessage()]); abort(404); } } }
5.检查是否有该作用域权限
if($request->user()->tokenCan('test1')){ }