【问题标题】:Using Laravel Auth middleware使用 Laravel Auth 中间件
【发布时间】:2015-11-16 20:05:52
【问题描述】:

Laravel 5.1 的文档真的很少。。 我需要清楚地了解如何使用 Auth middileware 保护路由..

文档告诉向路由添加“中间件”=>“auth”参数。 还是可以的

    public function __construct() 
    {
      $this->middleware('auth');
    }

但是如何使用 Auth 中间件进行实际的用户身份验证以及从受保护的路由自动重定向到 /login 呢?

【问题讨论】:

    标签: php laravel authentication middleware laravel-5.1


    【解决方案1】:

    在 Kernel.php - 在受保护的 $routeMiddleware 下有注册的中间件,如下所示:

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    ];
    

    您可以看到 'auth' 已注册使用 App\Http\Middleware\Authenticate。

    那么你可以按照这个路径——如果你打开/app/Http/Middleware/Authenticate.php, 你会发现公共函数句柄:

        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if ($this->auth->guest())
            {
                if ($request->ajax())
                {
                    return response('Unauthorized.', 401);
                }
                else
                {
                    return redirect()->guest('auth/login');
                }
            }
    
            return $next($request);
        }
    

    这里是管理重定向的地方,您可以根据自己的需要对其进行修改,也可以创建自定义中间件。

    最后 - 正如文档中所写 - 在需要验证的控制器中,您将添加

    public function __construct() 
    {
      $this->middleware('auth');
    }
    

    如果提供的中间件不适合您的需求,您可以创建自定义中间件。

    【讨论】:

    • 我已经这样做了..所有..我想留下一些东西..因为我的控制器 url 没有重定向到访客的登录 url..我正在使用使用资源控制器命令创建的控制器跨度>
    • 那么是路由问题吗?也许您需要自定义路线?
    • Route::group(['prefix' => 'user'], function() { Route::get('/', ['uses' => 'UserController@index']) ; Route::match(['get'], '/logout', ['uses' => 'UserController@logout']); Route::match(['post', 'get'], '/login' , ['uses' => 'UserController@login']); Route::match(['post', 'get'], 'register', array('uses' => "UserController@register")); 路由::get('/profile', array('uses' => "UserController@profile")); });
    • 我的错.. 可能它现在可以工作了.. 现在我的页面进入了无限重定向循环.. 可能是因为我在所有操作中都使用了自定义重定向。 “页面未正确重定向”
    • 好,但是你为什么不使用路由:Route::resource('/', 'UserController', ['only' => ['index','logout','register ', '个人资料']]);
    【解决方案2】:

    在 laravel 5.2 上,如果您想隐藏注册表单或登录表单视图,您应该将中间件用作:

    $this->middleware('mymiddleware', ['only' => ['register', 'showRegistrationForm', 'login', 'showLoginForm']]);
    

    $this->middleware('mymiddleware', ['except' => ['register', 'showRegistrationForm', 'login', 'showLoginForm']]);
    

    这是因为注册和登录路由是 AuthController 上的 post 方法,而 showXxxxForm 是表单视图。

    希望对大家有所帮助。

    【讨论】:

      【解决方案3】:

      在 Laravel 中,中间件用于某些路由只有用户登录才能访问,否则会重定向到登录页面。

      Auth::routes();
      Route::middleware(['auth'])->group(function () {
      //After Login the routes are accept by the loginUsers...
      
      }
      Route::middleware(['admin'])->group(function(){
      //the Admin is logged in to access the Routes...
      }
      

      【讨论】:

        【解决方案4】:

        //使用中间件进行登录认证

        1) 制作中间件:

        php artisan make:middleware adminAuth
        

        2) 写入中间件文件:

        <?php
        
        namespace App\Http\Middleware;
        
        use Closure;
        use Illuminate\Http\Request;
        use Illuminate\Support\Facades\Auth;
        class loginAuth
        {
            /**
             * Handle an incoming request.
             *
             * @param  \Illuminate\Http\Request  $request
             * @param  \Closure  $next
             * @return mixed
             */
            public function handle(Request $request, Closure $next)
            {
                $isAuthenticatedAdmin = (Auth::check());
        
                //This will be excecuted if the new authentication fails.
                if (!$isAuthenticatedAdmin){
        
                    return redirect()->route('login')->with('message', 'Authentication Error.');
                }
                return $next($request);
        
            }
        }
        

        3) 在下面一行添加 app/http/kernal.php

        protected $routeMiddleware = [
          'adminAuth' => \App\Http\Middleware\AdminAuth::class //Registering New Middleware
        ];
        

        4)在中间件中添加路由:

        Route::get('login',[AuthController::class,'index'])->name('login'); //named route
        
        Route::get('dashboard',function(){
            return view('admin-page.dashboard');
        })->middleware("adminAuth");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-19
          • 2021-06-11
          • 1970-01-01
          • 2017-04-24
          • 2016-03-07
          • 1970-01-01
          • 1970-01-01
          • 2018-02-13
          相关资源
          最近更新 更多