This implements a simple basic authentication without logging into the application itself so you can browse the application itself as a guest user, too. Works like a charm instead of using .htaccess file.
Implemented as a custom middleware in app/Http/Kernel.php to the web group in $middlewareGroups
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
class ProtectDevServers
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if(env('APP_ENV') != 'production')
{
if(Request::getUser() != 'foo' || Request::getPassword() != 'bar'){
$headers = array('WWW-Authenticate' => 'Basic');
return Response::make('Invalid credentials.', 401, $headers);
}
}
return $next($request);
}
}