Laravel Middleware & Basic Auth Implementation

Faysal Ahmed
Oceanize Lab Geeks
Published in
2 min readJan 29, 2018

When we develop any web application with laravel, we have to manage a lot of requests. Most of the time each request need to maintain with a specific filter requirements. In this context laravel provide Middleware with a very convenient way to manage application request.

What Middleware Does?

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Today i will show you how Middleware works & how to create a Middleware with basic authentication mechanism and successfully implement in your laravel application.

Implementing Basic Authentication in middleware

For this article i am using laravel 5.5.
Basically all the Middleware files are located in app/Http/Middleware directory. So our newly created Middleware file will also have to put inside app/Http/Middleware directory.

The artisan command for create new Middleware is make:middleware .

We will create a Middleware which will responsible for BasicAuth. To create a new middleware name BasicAuth run command php artisan make:middleware BasicAuth after that it will create a middlware class BasicAuth.php inside app/Http/Middleware directory.

After successfully created BasicAuth.php file it’s look like below

<?phpnamespace App\Http\Middleware;use Closure;class BasicAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}

Then we will create mechanism for basic auth.

<?phpnamespace App\Http\Middleware;use Closure;class BasicAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$AUTH_USER = 'admin';
$AUTH_PASS = 'admin';
header('Cache-Control: no-cache, must-revalidate, max-age=0');
$has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));
$is_not_authenticated = (
!$has_supplied_credentials ||
$_SERVER['PHP_AUTH_USER'] != $AUTH_USER ||
$_SERVER['PHP_AUTH_PW'] != $AUTH_PASS
);
if ($is_not_authenticated) {
header('HTTP/1.1 401 Authorization Required');
header('WWW-Authenticate: Basic realm="Access denied"');
exit;
}
return $next($request);
}
}

After implementing Basic Auth mechanism we have to now register this middleware on app/Http/Kernel.php

protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'basicAuth' => \App\Http\Middleware\BasicAuth::class //Registering New Middleware
];

After registering Middlware now we can use this in routes/web.php

Route::middleware(['basicAuth'])->group(function () {
//All the routes are placed in here
Route::get('/', 'LoginController@index');
Route::get('/home', 'DashboardController@dashboard');
});

After that if we try to visit out site it will open with a popup for asking basic Authentication.

Popup window for basic authentication

This is a very simple implementation of middleware with a basic authentication. Middleware has truly some advanced functionalities. Hopefully it will help for gasp understanding about middleware.

--

--