[英]Laravel Middleware not working on some resource route
我正在按照教程进行访问级别限制:
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
我希望它仅在索引中。
我的代码:
内核.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;
}
}
您可以尝试一下,创建一个构造函数,然后从那里添加中间件,例如:
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
}
您也可以在我的博客(关于中间件)上查看这些示例/教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.