Route protection with middleware

Published 6 months ago by dokunbam

I want to protect dashboard so that if you don't login you cant access the dashboard route. user to be redirected if not signed in

Middleware/CheckUser.php

<?php

namespace App\Http\Middleware;

use Closure;

class CheckUsers
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::guard($guard)->guest())
        {
            if($request->ajax())
            {
                return response('Unauthorised.', 401);
            }else{
                return redirect()-route('home');
            }
        }
        return $next($request);
    }
}

routes/web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(['middleware' => ['web']], function(){

    Route::get('/', function () {
    return view('home');
     });

 
    Route::post('/signup', [
        'uses' => '[email protected]',
        'as'   => 'signup'
    ]);

    Route::get('/dashboard', [
        'uses' => '[email protected]',
        'as'   => 'dashboard',
    ]);

    Route::post('/signin', [
        'uses' => '[email protected]',
        'as'   => 'signin',
        'middleware' => 'auth'
    ]);
});
Best Answer (As Selected By dokunbam)
tykus

Where do you want to redirect an unauthenticated user - I don't see a GET route for signing in.

You can catch the thrown AuthenticationException inside the app/Exceptions/Handler.php class and redirect wherever you like:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
            return redirect('route-name-here');
        }
        return parent::render($request, $exception);
    }
tykus
tykus
6 months ago (574,630 XP)

You know there is an inbuilt auth middleware, right?

burlresearch

Also, in web/routes.php there is no need to group your routes in 'web' middleware - any routes in this file already are, by definition, see:

  • \App\Providers\RouteServiceProvider::mapWebRoutes

So, as @tykus suggests, all you need to do is put the route you want to protect in 'auth' middleware:

Route::get('/dashboard', ... )->middleware('auth');
dokunbam

According to @burlresearch

I did this

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(['middleware' => ['web']], function(){

    Route::get('/', function () {
    return view('home');
     });

 
    Route::post('/signup', [
        'uses' => '[email protected]',
        'as'   => 'signup'
    ]);

    Route::post('/signin', [
        'uses' => '[email protected]',
        'as'   => 'signin',
    ]);
});


Route::get('/dashboard', [
    'uses' => '[email protected]',
    'as'   => 'dashboard',
])->middleware('auth');

But still not working. Pardon me I am new to laravel and PHP

tykus
tykus
6 months ago (574,630 XP)

What is it doing if it is not working?

dokunbam

I don't want users to visit /dashboard directly without logging in.

I can still access the link directly by typing the link into the address bar. I will be directed to the dashboard.

When I type this localhost:8000/home/dashboard, I am directed straight to the dashboard without logging in

tykus
tykus
6 months ago (574,630 XP)

You do not have a route defined for this URL: http://localhost:8000/home/dashboard; your auth-protected dashboard be http://localhost:8000/dashboard

dokunbam

@tykus Sorry it http://localhost:8000/dashboard

But I am getting

Route [login] not defined."

tykus
tykus
6 months ago (574,630 XP)

Where do you want to redirect an unauthenticated user - I don't see a GET route for signing in.

You can catch the thrown AuthenticationException inside the app/Exceptions/Handler.php class and redirect wherever you like:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
            return redirect('route-name-here');
        }
        return parent::render($request, $exception);
    }
Snapey
Snapey
6 months ago (929,845 XP)

You were advised not to specify web route middleware, but I notice you still have

Route::group(['middleware' => ['web']], function(){

dokunbam

@Snapey Thanks for the observation

I am still getting

"Route [login] not defined."

after doing this

    Route::get('/', function () {
    return view('home');
     });

 
    Route::post('/signup', [
        'uses' => '[email protected]',
        'as'   => 'signup'
    ]);

    Route::post('/signin',
        [
        'uses' => '[email protected]',
        'as'   => 'signin'
        ]
    );

Route::get('dashboard', [
        'uses' => '[email protected]',
        'as'   => 'dashboard'
    ])->middleware('auth'); 

I tried several things to redirect back or to 'home' route Do I need to create another home route? What am I doing wrong?

I tried this as well

    Route::get('/', function () {
    return view('home');
     });

 
    Route::post('/signup', [
        'uses' => '[email protected]',
        'as'   => 'signup'
    ]);

    Route::post('/signin',
        [
        'uses' => '[email protected]',
        'as'   => 'signin'
        ]
    );

Route::get('dashboard', [
        'uses' => '[email protected]',
        'as'   => 'dashboard'
    ])->middleware('auth')->redirect()->back();
tykus
tykus
6 months ago (574,630 XP)

Did you catch the Authentication exception as I described earlier?

Also, you need to name a route as home, which you appear not to have done yet.

Route::get('/', function () {
    return view('home');
})->name('home');

dokunbam

@tykus Thanks. its working fine now

I was just trying to do something simple.

Let say I want to protect and redirect another route like http://localhost:8000/dashboard/user-manual/user-settings (I can certainly create the route)

I want to redirect users to http://localhost:8000/dashboard/user-manual to perform a certain task before they can go to

http://localhost:8000/dashboard/user-manual/user-settings

How would I add to the existing Authentication exception in Handler.php?

public function render($request, Exception $exception)
    {
        if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
            return redirect('login');
        }

        return parent::render($request, $exception);
    }
tykus
tykus
6 months ago (574,630 XP)

Not sure I understand what ou are trying to achieve; unless a certain task is to sign in, then you would not be looking to catch an AuthenticationException in that case.

Please sign in or create an account to participate in this conversation.