Using Laravel Auth middleware

51,534

Solution 1

In Kernel.php - there are registered middlewares under protected $routeMiddleware like this:

/**
 * 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',
];

You can see 'auth' is registered for using App\Http\Middleware\Authenticate.

Then you can follow this path - if you open /app/Http/Middleware/Authenticate.php, you will find public function handle:

    /**
     * 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);
    }

and here is where redirection is managed, and you can modify it for your own needs, or you can create custom middleware.

finally - as it is written in documentation - in the controller, which will need to be authenticated, you will add

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

You can create a custom middleware if provided ones do not suit your needs.

Solution 2

On laravel 5.2 if you want to hide the registration form or the login form views you should use your middleware as:

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

OR

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

That is because the register and login routes are the post methods on the AuthController while showXxxxForm are the form views.

Hope it helps anyone.

Share:
51,534
harish
Author by

harish

Updated on December 09, 2021

Comments

  • harish
    harish over 2 years

    Laravel 5.1 really had minimal documentation.. I need clear idea about how to protect routes using Auth middileware..

    Documentation tells to add "middleware" => "auth" parameter to route. or can do

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

    But How to use Auth middleware for actual user authentication and auto redirection to /login from protected routes ??

  • harish
    harish over 8 years
    I already did this..all.. I was thinking left something..as my controller urls are not redirecting to login url for guests.. I am using controller created using command for resource controller
  • Angel M.
    Angel M. over 8 years
    so is a routing issue? maybe you need to customize routes?
  • harish
    harish over 8 years
    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")); Route::get('/profile', array('uses' => "UserController@profile")); });
  • harish
    harish over 8 years
    My bad.. May be its working now.. Now my page entered in to infinite redirection loop.. may be because i used custom redirection in all actions. "The page isn't redirecting properly"
  • Angel M.
    Angel M. over 8 years
    good, but why don't you use routes as : Route::resource('/', 'UserController', ['only' => ['index','logout','register', 'profile']]);
  • harish
    harish over 8 years
    Route::resource(... Not working and "The page isn't redirecting properly" problem persists..... :(
  • Angel M.
    Angel M. over 8 years
    try to use it like: Route::group(['prefix' => 'user'], function() { Route::get('/', ['uses' => 'UserController@index']); Route::get('/logout', ['uses' => 'UserController@logout']); Route::get('/login', ['uses' => 'UserController@login']); Route::get('/register', ['uses' => 'UserController@register']); Route::get('/profile', ['uses' => "UserController@profile"]); }); hm, I'm not sure as I don't know what you have in UserController. For example, for post actions I use different methods like 'postLogin'...
  • harish
    harish over 8 years
    Issue is resolved now for me.. codeheaps.com/php-programming/… was helpfull
  • Angel M.
    Angel M. over 8 years
    @harish this is great
  • harish
    harish over 8 years
    Actually Laravel 5 is awesome.. PHP Namespaces is what you should have strong understanding about.
  • Angel M.
    Angel M. over 8 years
    yes, it is. And working with namespaces is really amazing - this way I can import external libraries without any special effort.