EventFellows's avatar

Limit access to Test and DEV environments without .htaccess

I waneted to limit access to my test and development servers / environments so only the production system would be freely accessible to users. As I had to learn: .env variables are not accessible on the server itself to be picked up by the .htaccess file (for apache server) so the basic authentication can only be handled there with weird work-arounds.

I looked for a way to solve it Laravel internal so it also becomes part of version controll. Here is my setup for users to use.

0 likes
1 reply
EventFellows's avatar
EventFellows
OP
Best Answer
Level 16

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

Please or to participate in this conversation.