This commit is contained in:
ct
2025-07-15 20:03:10 +08:00
parent b54e4f2092
commit 096f515f58
15 changed files with 1161 additions and 3 deletions

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class BasicAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$username = env('BASIC_AUTH_USERNAME');
$password = env('BASIC_AUTH_PASSWORD');
// If credentials are not set, deny access
if (! $username || ! $password) {
return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
}
// Check if Authorization header is present
if (! $request->header('Authorization')) {
return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
}
// Extract credentials from Authorization header
$authHeader = $request->header('Authorization');
if (! str_starts_with($authHeader, 'Basic ')) {
return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
}
$credentials = base64_decode(substr($authHeader, 6));
[$inputUsername, $inputPassword] = explode(':', $credentials, 2);
// Verify credentials
if ($inputUsername !== $username || $inputPassword !== $password) {
return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
}
return $next($request);
}
}