Description
I wanted to add just basic authentication on whole page.
(It's not for user authentication)
Preparation
$ php artisan make:middleware BasicAuthMiddleware
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\BasicAuthMiddleware::class, // Add here
];
...
Create Config
Add environment parameter for basic authentication
.env
...
BASIC_AUTH_FLAG=1
BASIC_AUTH_PASSWORD=sample
BASIC_AUTH_USER=sample
$ vim config/myauth.php
config/myauth.php
<?php
return [
'basic' => [
'flag' => env('BASIC_AUTH_FLAG', 0),
'username' => env('BASIC_AUTH_USER', null),
'password' => env('BASIC_AUTH_PASSWORD', null)
]
];
Edit code
app/Http/MiddleWare/BasicAuthMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class BasicAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (config('myauth.basic.flag')){
switch (true) {
case !isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']):
case $_SERVER['PHP_AUTH_USER'] !== config('myauth.basic.username'):
case $_SERVER['PHP_AUTH_PW'] !== config('myauth.basic.password'):
header('WWW-Authenticate: Basic realm="Enter username and password."');
header('Content-Type: text/plain; charset=utf-8');
die('You do not have permission');
}
header('Content-Type: text/html; charset=utf-8');
}
return $next($request);
}
}
Usage
If you'd like to verify user, change BASIC_AUTH_FLAG on env.