【问题标题】:Middleware on route level based on multiple user roles基于多用户角色的路由级中间件
【发布时间】:2018-09-08 05:35:42
【问题描述】:

我在laravel 应用程序中有大约 10 种用户角色,例如

  user_type_1 and user_type 4 are accessing url-1.
  user_type_7, user_type_5 and user_type 4 are accessing url-2.
  user_type_5, user_type_1, user_type_3 and user_type 6 are accessing url-3.
  ............................................
  ............................................
   n number of combination of routes. url according to user type.

我的route/web.php 文件有大约 1500 条路由,目前没有使用中间件分隔为组。我必须将用户限制为仅对那种 user_type 授权的 url。您能否建议任何更好的方法来执行此操作。

我曾尝试将 url 与下面的中间件组组合在一起,但经过一些工作后,这种方法就离开了。

Route::group(['middleware' => ['middleware_user_type_1', 'middleware_user_type_2']], function () {
        Route::get('url-1', 'XYZController@someMethod');
    });

以这种方式,请求首先进入数组中的第一个中间件,如果用户类型无效,则不要尝试使用第二个中间件。

【问题讨论】:

  • 您是否在控制器的 __construct() 中尝试过这个?您是否已正确配置角色和用户以在中间件阵列中单独指定它们?你有 Laratrust 吗?或保镖Spatie

标签: php laravel routes laravel-routing laravel-middleware


【解决方案1】:

您需要实现一个中间件并将用户类型传递给它。

Route::group(['middleware' => ['check_user_type:type_1,type_2']], function () {
        Route::get('url-1', 'XYZController@someMethod');
    });

看看spatie/laravel-permission角色中间件是如何实现类似的逻辑的。

Route::group(['middleware' => ['role:super-admin|writer']], function () {
    //
});

中间件然后通过分隔符分解角色字符串,然后检查当前用户是否具有任何角色。

【讨论】:

  • 在这种情况下中间件的逻辑是什么。我认为它会检查提供的用户类型中的身份验证用户类型。
  • 我更新了答案,添加了一个例子来澄清它。
  • 谢谢,这对我有用。尝试使用一些路线。
【解决方案2】:

您可以在路由组中定义中间件和角色。首先,您在中间件中定义角色管理。

Route::group(['middleware' => ['roles'], 'roles' => ['role_1','role_2], function () {
    Route::get('/index', [
        'uses' => 'ExampleController@index',
        'as'=> 'index'
    ]);
});

【讨论】:

    【解决方案3】:

    您可以开箱即用地实施政策:

    https://laravel.com/docs/5.6/authorization#creating-policies

    问候。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 2015-01-30
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2016-06-12
      • 2012-01-01
      • 1970-01-01
      相关资源
      最近更新 更多