Sometimes you'd like to have very simple and basic authentication similar to HTTP basic authentication applied to a directory. For example you'd like to protect an API accessible under https://www.example.com/secret-api. Obviously when using Laravel routes you can not use .htpasswd file to password protect it as the secret-api directory doesn't exist on the server disk. Instead you can use Laravel's middleware and very simply get the same result.

Add the route to your routes.php file:

 

Route::resource('secret-api', 'SecretApiController');

Create middleware with Artisan.

From command line change current directory to the root directory of you're project and execute following command: 

$ php artisan make:middleware ApiSimpleAuth

 It will create ApiSimpleAuth.php file in ../App/Source Files/Http/Middleware/ directory. Open the file and change it to look like below and save it: 

/** 
* Handle an incoming request. * 
* @param \Illuminate\Http\Request $request 
* @param \Closure $next 
* @return mixed 
*/ 

   public function handle($request, Closure $next)
   {
      if (Request::getUser() != 'foo' || Request::getPassword() != 'bar') {
            $headers = array('WWW-Authenticate' => 'Basic'); return Response::make('Invalid credentials.', 401, $headers);
      }

   return $next($request);
   }

}

Register your middleware.

In Kernel.php file add following line to the $routeMiddleware property: 

'api.simple.auth' => \App\Http\Middleware\ApiSimpleAuth::class,

 So it can look like this: 

/** 
* The application's route middleware. * 
* @var array 
*/ 

protected $routeMiddleware = [

    'auth' => \App\Http\Middleware\Authenticate::class, 
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 
    'api.simple.auth' => \App\Http\Middleware\ApiSimpleAuth::class, 

];

Turn the authentication on in your controller.

The last thing left is to tell the controller to use the middleware we have created. It's as simple as adding a constructor to the controller class as follows: 

public function __construct() 
{
      $this->middleware('api.simple.auth');
}

   That's it. Now if you try to access https://www.example.com/secret-api you'll be asked for user and password first.