Laravel - How to redirect to login if user is not authenticated

后端 未结 4 1815
悲&欢浪女
悲&欢浪女 2021-02-13 19:26

I\'m trying to use the __constructor from the extended class (AdminController extends AdminBaseController) but aparently it\'s not working

相关标签:
4条回答
  • 2021-02-13 20:07

    Use middleware for this purpose and then in controller constructor use it as in example below.

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
    

    And then you need to secure routes where you want from user to be logged in to access.

    Route::group(['middleware' => 'auth'], function() {
          Route::get('/dashboard', 'DashboardController@index');
    });
    
    0 讨论(0)
  • 2021-02-13 20:08

    The way you extends and execute the parent constrictor is right, however returning a view to execute it is only possible from routes, controller actions and filters. Otherwise you have to call send().

    for you purpose I think you should use before for filter http://laravel.com/docs/4.2/routing#route-filters

    0 讨论(0)
  • 2021-02-13 20:11

    The controller is not the right place to check if a user is authenticated or not. You should use a middleware for that. To get info on what a middleware is check here

    Let's see how you can use the default Laravel's auth middleware for this purpose:

    First of all get rid of your AdminBaseController and use only AdminController

    Then you have to check that the auth middleware is enabled in the file app\Http\Kernel.php

    You should have the line:

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
    

    This means that the middleware is active and usable for your routes.

    Now let's go inside the middleware class in app\Http\Middleware\Authenticate.php to specify the middleware's behaviour :

    //this method will be triggered before your controller constructor
    public function handle($request, Closure $next)
    {
        //check here if the user is authenticated
        if ( ! $this->auth->user() )
        {
            // here you should redirect to login 
        }
    
        return $next($request);
    }
    

    Now the only thing left to do is to decide for what routes you should apply the middleware. Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way:

    Route::group( ['middleware' => 'auth' ], function()
    {
        Route::get('admin/index', 'AdminController@index');
        Route::get('admin/ajuda', 'AdminController@ajuda');
    });
    
    0 讨论(0)
  • 2021-02-13 20:32

    In Laravel 5.5 , an unauthenticated user will cause the Authenticate middleware to throw a AuthenticationException exception.

    protected function authenticate(array $guards)
    {
     if (empty($guards))
     {
      return $this->auth->authenticate();
     }
     foreach ($guards as $guard) {
      if ($this->auth->guard($guard)->check()) {
          return $this->auth->shouldUse($guard);
      }
     }
     throw new AuthenticationException('Unauthenticated.', $guards);
    }
    

    This will be caught by the app/Exceptions/Handler class which will call its render method which is responsible for converting a given exception into a HTTP response.

    public function render($request, Exception $exception)
    {
     return parent::render($request, $exception);
    }
    

    App/Exceptions/Handler extends 'Illuminate\Foundation\Exceptions\Handler', located inside '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler'. It has its own render method. Within that render method, there's a if else statement that says.

    elseif ($e instanceof AuthenticationException)
    {
     return $this->unauthenticated($request, $e);
    }
    

    Below is the ‘unauthenticated‘ method that is called by the above within the same class

    protected function unauthenticated($request, AuthenticationException $exception)
    {
      return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(route('login'));
    }
    

    within this method is where you redirect an unauthenticated user.

    As far as I can see, this is what goes on behind the scenes.

    0 讨论(0)
提交回复
热议问题