【问题标题】:Prevent role-specific users from accessing route阻止特定角色的用户访问路由
【发布时间】:2020-01-31 12:06:07
【问题描述】:

我有两个角色,即adminuser。现在登录时,管理员转到dashboard 路由,而用户转到home。当用户登录并将 url 更改为http://127.0.0.1:8000/dashboard 时,它可以访问管理员面板,我不希望这样。我怎样才能做到这一点?

附言。我是 Laravel 的新手

【问题讨论】:

    标签: laravel laravel-5 routes laravel-authorization


    【解决方案1】:

    最好的做法是使用 Middewares。 为管理员和用户创建中间件(我只会为管理员做,你可以为用户做同样的事情):

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth;
    
    class AdminMiddleware
    {
        public function handle($request, Closure $next)
        {
            if(Auth::check()){
                // check auth user role (I don't know how you can implement this for yourself, this is just for me)
                if(Auth::user()->role->name == 'admin'){
                    return $next($request);
                } else {
                    return redirect()->route('admin.dashboard'); // for admins
                }
            }
    
            return redirect()->route('main'); // for users
        }
    }
    

    在 $routeMiddleware 数组的“app/Http/Kernel.php”中注册(添加到该数组的末尾)。

    'Admin' => \App\Http\Middleware\AdminMiddleware::class,
    

    现在,如果您在“routes/web.php”中使用所有请求(实际上我认为确实如此),那么您可以为管理员使用这样的路由:

    // USER ROUTES
    Route::get('/', 'FrontController@main')->name('main');
    
    // ADMIN ROUTES
    Route::group([
        'as' => 'admin.',
        'middleware' => [ 'Admin' ],
    ], function () {
        Route::get('dashboard', 'AdminController@dashboard');
    });
    

    通过“php artisan config:cache”刷新缓存。 试试看!

    【讨论】:

    • Auth::check()有什么用?
    • 好的,我现在可以正常工作了,明天会尝试测试一切是否正常。很高兴第一次尝试就可以使用!非常感谢!一定会记住这一点!
    【解决方案2】:

    使用中间件管理路由或在控制器内部 像这样:

    Route::put('post/{id}', function ($id) {
    //
    })->middleware('role:editor');
    

    Route::middleware(['auth', 'admin'])->group(function (){
    
    Route::get('dashboard', 'HomeController@index')->name('home.index');
    
    });
    

    或者像这样在控制器内部:

    public function __construct()
    {
        $this->middleware(['auth', 'admin'])->except(['index']);
    }
    

    或者您可以使用this 作为中间件角色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      相关资源
      最近更新 更多