我正在关注制定访问级别限制的教程:
https://gist.github.com/amochohan/8cb599ee5dc0af5f4246
我能够以某种方式使它工作,但我需要做的事情,而不是在教程中。
前提是我已按照本教程进行操作。我已经设置了这条资源路线:
Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
Route::resource('changeschedule', 'ChangeScheduleController', ['only' => ['index'], 'except' => ['create']]);
});
所以我想要的只是将roles
中间件应用于资源路由,但在该资源中使用特定路由只是让我说我只想应用于index
我上面有这条路线。
当我去:
http://localhost/hrs/public/changeschedule
它工作正常,中间件roles
工作正常。但是当我去的时候为什么呢?
http://localhost/hrs/public/changeschedule/create
我正在
NotFoundHttpException in RouteCollection.php line 161:
所以我找不到路线错误。这是为什么?但是当我做的时候
Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
Route::resource('changeschedule', 'ChangeScheduleController');
});
然后它工作正常,但中间件应用于所有:
index, create, update, edit, delete
我希望它只在索引中。
我的代码:
Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'roles' => \App\Http\Middleware\CheckRole::class,
];
CheckRole.php
<?php namespace App\Http\Middleware;
use Closure;
class CheckRole{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Get the required roles from the route
$roles = $this->getRequiredRoleForRoute($request->route());
// Check if a role is required for the route, and
// if so, ensure that the user has that role.
if($request->user()->hasRole($roles) || !$roles)
{
return $next($request);
}
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles'] : null;
}
}
答案 0 :(得分:0)
您可以尝试这个,创建一个构造函数并从那里添加中间件,例如:
public function __construct()
{
$this->middleware('auth');
$this->middleware('roles:administrator', ['only' => ['index']]);
}
更新(middleware :: handle方法中的第三个参数可以接受参数):
public function handle($request, Closure $next, $role)
{
// $role will catch the administrator or whatever you pass
}
您也可以在我的博客上查看这些examples/tutorials(关于中间件)。