简体   繁体   English

限制对非管理员用户的路由访问

[英]Restrict route access to non-admin users

Goal 目标

I'm trying to create Admin route restriction for my log-in users. 我正在尝试为我的登录用户创建管理员路由限制。 I've tried a check to see if my user is log-in , and also if the user type is Admin , and if they are, I want to allow them access to the admin route, otherwise, respond a 404. 我尝试检查一下我的用户是否log-in ,以及用户类型是否为Admin ,如果是,我希望允许他们访问管理路由,否则,响应404。


routes.php routes.php

<!-- Route group -->
$router->group(['middleware' => 'auth'], function() {


    <!-- No Restriction -->
    Route::get('dashboard','WelcomeController@index');

    <!-- Admin Only -->
    if(Auth::check()){
        if ( Auth::user()->type == "Admin" ){

            //Report
            Route::get('report','ReportController@index');
            Route::get('report/create', array('as'=>'report.create', 'uses'=>'ReportController@create'));
            Route::post('report/store','ReportController@store');
            Route::get('report/{id}', array('before' =>'profile', 'uses'=>'ReportController@show'));
            Route::get('report/{id}/edit', 'ReportController@edit');
            Route::put('report/{id}/update', array('as'=>'report.update', 'uses'=>'ReportController@update'));
            Route::delete('report/{id}/destroy',array('as'=>'report.destroy', 'uses'=>'ReportController@destroy'));

        }
    }

});

Result 结果

It's not working as I intended. 它没有按我的预期工作。 It throws 404 error - even for Admin users. 它将引发404错误-甚至对于Admin用户。

You can use Middleware for this simple case. 您可以在这种简单情况下使用中间件

  1. Create middleware: 创建中间件:
php artisan make:middleware AdminMiddleware
namespace App\Http\Middleware;

use App\Article;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class AdminMiddleware
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->getUser()->type !== "admin") {
            abort(403, 'Unauthorized action.');
        }

        return $next($request);
    }
}
  1. Add it to app\\Http\\Kernel.php : 将其添加到app\\Http\\Kernel.php
protected $routeMiddleware = [
    'admin' => 'App\Http\Middleware\AdminMiddleware',
];
  1. Use middleware in your routes: 在您的路线中使用中间件:
Route::group(['middleware' => ['auth', 'admin']], function() {
    // your routes
});

This answer is about why your code doesn't work as expected. 这个答案是关于为什么您的代码无法按预期工作的原因 @limonte 's solution is correct and the best I can think of. @limonte的解决方案是正确的,也是我能想到的最好的解决方案。

Your routes file is parsed to get your routes, and after that, those routes might be cached somewhere else. 解析路由文件以获取路由,然后,这些路由可能会缓存在其他位置。

Thus you shouldn't put any code that depends on the request (eg checking whether a User has sufficient rights to access a route). 因此,您不应放置任何依赖于请求的代码(例如,检查用户是否具有访问路径的足够权限)。

In particular, you shouldn't use the following request dependent modules inside your routes.php (not exhaustive) : 特别是,您不应在route.php中使用以下依赖于请求的模块(并非详尽无遗):

  • Auth
  • DB or any kind of db queries that might depend on time DB或可能取决于时间的任何类型的数据库查询
  • Session
  • Request

You should view your routes.php as part of your config, it just happens that it is written in php directly instead of some new language you have to learn. 您应该将routes.php作为配置的一部分进行查看,只是它是直接用php编写的,而不是您必须学习的一些新语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM