我正在尝试为我的laravel API实现角色和权限。我安装了包:
https://yajrabox.com/docs/laravel-acl/3.0/introduction
如果有人可以向我解释它是如何工作的,那将是很棒的,我想要做的就是在用户点击一条API路线时获得许可。 我不想在每个路由中设置中间件,因为我要做几个路由,每次设置中间件都会很痛苦,我想动态地做。
我试着自己做,但是没有用。这是我在Authserviceprovider中的代码:
public function boot(GateContract $gate)
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
$permissions = Permission::with('roles')->get();
foreach ($permissions as $permission)
{
$gate->define($permission->name, function (User $user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
我这样做:https://github.com/laracasts/laravel-5-roles-and-permissions-demo/tree/master/app
答案 0 :(得分:1)
您可以在web.php / api.php文件中使用中间件,例如下面的示例(web.php):
Route::group(['middleware' => ['verified']], function () {
Route::get('/', 'HomeController@index')->name('home');
});
正如我的示例所示,这将检查帐户是否已经过验证,然后才能查看“/”
<强>更新强>
这几乎与上述问题无关,但是Op在评论中提出了我的回答中的第二个问题:这是我的中间件代码,用于显示Op如何运行中间件:
public function handle($request, Closure $next)
{
$verified = Auth::user();
if ($verified->verified == 0)
{
Auth::logout();
Session::flash('error', "$verified->username, your email address hasn't been verified yet therefore you're unable sign in.");
return Redirect('/login');
}
return $next($request);
}