【发布时间】:2016-07-09 11:07:46
【问题描述】:
我正在按照教程进行访问级别限制:
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;
}
}
【问题讨论】:
标签: php laravel authentication laravel-middleware