11

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
  • 578
  • 2
  • 8
  • 21

4 Answers4

14

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.

Angel M.
  • 2,692
  • 2
  • 32
  • 43
  • 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 – harish Aug 23 '15 at 09:05
  • so is a routing issue? maybe you need to customize routes? – Angel M. Aug 23 '15 at 09:06
  • 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 Aug 23 '15 at 09:10
  • 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" – harish Aug 23 '15 at 09:14
  • good, but why don't you use routes as : Route::resource('/', 'UserController', ['only' => ['index','logout','register', 'profile']]); – Angel M. Aug 23 '15 at 09:15
  • Route::resource(... Not working and "The page isn't redirecting properly" problem persists..... :( – harish Aug 23 '15 at 10:15
  • 1
    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'... – Angel M. Aug 23 '15 at 11:02
  • Issue is resolved now for me.. http://www.codeheaps.com/php-programming/laravel-5-new-auth-generators-user-authentication/ was helpfull – harish Aug 24 '15 at 11:07
  • @harish this is great – Angel M. Aug 24 '15 at 11:09
  • 1
    Actually Laravel 5 is awesome.. PHP Namespaces is what you should have strong understanding about. – harish Aug 25 '15 at 08:01
  • yes, it is. And working with namespaces is really amazing - this way I can import external libraries without any special effort. – Angel M. Aug 25 '15 at 08:07
7

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.

2

In Laravel, Middleware is used make to some Routes are access only to the User when User is login, Otherwise it will redirect to the Login Page.

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...
}
Denusklo
  • 35
  • 5
Vignesh
  • 174
  • 1
  • 5
0

//login authentication using middleware

1) make middleware:

php artisan make:middleware adminAuth

2) write in middleware file:

<?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) add app/http/kernal.php inside below line

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

4)add routes in middleware:

Route::get('login',[AuthController::class,'index'])->name('login'); //named route

Route::get('dashboard',function(){
    return view('admin-page.dashboard');
})->middleware("adminAuth");