How to implement basic auth in laravel middleware.

Muhammad Eddo Gustian
2 min readSep 21, 2020

Implementing Basic Authentication in middleware

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.

<?php namespace 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

rotected $routeMiddleware = [
'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

don’t forget to add an index method to app/Http/Controller/Auth/LoginController.php

/*** Show the login page.** @return \Illuminate\Contracts\Support\Renderable*/public function index()
{
return view('auth.login');
}

--

--