Laravel 内置的权限 middleware
查看 app/Http/Kernel.php,可以看到 middleware can。可以用于权限的检查
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
backpack admin CRUD 路由的设置
例如,为管理员添加“全部功能”权限之后,就可以在路由中进行限制
routes/admin.php
Route::group(['middleware' => ['can:全部功能']], function () {
CRUD::resource('goods_category', 'GoodsCategoryCrudController');
});
不要漏了用户、权限、角色路由的保护
routes/backpack/permissionmanager.php
Route::group([
'namespace' => 'App\Http\Controllers\Admin',
'prefix' => config('backpack.base.route_prefix', 'admin'),
'middleware' => ['web', 'admin', 'can:全部功能'],
], function () {
CRUD::resource('permission', 'PermissionCrudController');
CRUD::resource('role', 'RoleCrudController');
CRUD::resource('user', 'UserCrudController');
});
如果要使用角色方式进行控制
上面是使用权限的检查来进行限制,也可以使用角色的检查来达到相同的效果。
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
if (Auth::guest()) {
return redirect('login');
}
if (! $request->user()->hasRole($role)) {
abort(403);
}
return $next($request);
}
}
微信关注我哦 👍
我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式