Php 用于检查用户角色的laravel路由筛选器
我正在Laravel4中构建一个RESTfulAPI,其中有具有不同类型权限的用户。我想根据用户角色(保存在数据库的用户表中)限制对不同路由的访问 我该怎么做?这是我到目前为止所做的(到目前为止还不起作用) filters.phpPhp 用于检查用户角色的laravel路由筛选器,php,laravel,laravel-4,laravel-routing,Php,Laravel,Laravel 4,Laravel Routing,我正在Laravel4中构建一个RESTfulAPI,其中有具有不同类型权限的用户。我想根据用户角色(保存在数据库的用户表中)限制对不同路由的访问 我该怎么做?这是我到目前为止所做的(到目前为止还不起作用) filters.php //allows backend api access depending on the user's role once they are logged in Route::filter('role', function() { return Auth::user
//allows backend api access depending on the user's role once they are logged in
Route::filter('role', function()
{
return Auth::user()->role;
});
routes.php
Route::group(array('before' => 'role'), function($role) {
if($role==1){
Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single');
Route::post('customer/create', 'CustomerController@create');
Route::put('customer/update/{id}', 'CustomerController@update');
}
});
是否可能是我为“组筛选器”编写的语法错误?请尝试以下操作:
filters.php
Route::filter('role', function()
{
if ( Auth::user()->role !==1) {
// do something
return Redirect::to('/');
}
});
Route::group(array('before' => 'role'), function() {
Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single');
Route::post('customer/create', 'CustomerController@create');
Route::put('customer/update/{id}', 'CustomerController@update');
});
routes.php
Route::filter('role', function()
{
if ( Auth::user()->role !==1) {
// do something
return Redirect::to('/');
}
});
Route::group(array('before' => 'role'), function() {
Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single');
Route::post('customer/create', 'CustomerController@create');
Route::put('customer/update/{id}', 'CustomerController@update');
});
对于启动路由筛选器接受参数,可以采用不同的方法实现此功能:
Route::filter('role', function($route, $request, $value)
{
//
});
Route::get('someurl', array('before' => 'role:admin', function()
{
//
}));
上面的代码将在Route::filter中注入admin,可通过$value参数访问。
如果需要更复杂的筛选,您可以始终使用自定义路由筛选类(检查筛选类):
您还可以在控制器内进行过滤,这在需要基于特定控制器和方法进行过滤时提供了更好的方法:
最后,您可以使用Sentry2之类的工具,它提供了一个完整的RBAC解决方案,可在您的项目中使用:
从laravel 5.1.11中,您可以使用AuthServiceProvider:准确地说……它应该可以工作。。。。但是如果您需要为多个角色执行此操作,我们需要更改筛选器路由,例如
route::filter('role',function(){$roles=['2','3','4'];if(!in_array(Auth::user()->role,$roles)){返回重定向:到('/');})代码>