Laravel 5.5 require auth in staging

556 views Asked by At

I have a project with a few packages that have routes. I have a staging/demo environment that needs to be publicly accessible.

Is there a way to require the auth middleware (or something similar) for all routes without putting it on all of the individual routes and route groups? (Thinking something in bootstrap??)

1

There are 1 answers

3
Zenobia Panvelwalla On BEST ANSWER

If you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    YOUR MIDDLEWARE::class,
];

If you do not have access, or do not want, to modify the package controllers, you can create a Middleware (recommend inheriting from AuthenticateSession. For example:

<?php

namespace App\Http\Middleware;

use Illuminate\Session\Middleware\AuthenticateSession;

use Auth;
use Closure;

class AuthenticateIfEnvironment extends AuthenticateSession
{
    public function handle($request, Closure $next)
    {
        if (env('APP_ENV') == 'XXXXXXXX' && !Auth::user() && !$request->is('login')) {
            return redirect('/login');
        }
        return parent::handle($request, $next);
    }
}

Then Kernal.php looks like this:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\AuthenticateIfEnvironment::class,
];