Securing sensitive areas of a website is paramount, especially when dealing with sensitive data or functionalities. In this article, we'll explore a robust and efficient method for controlling access to specific pages in your Laravel application using IP address whitelisting. This approach goes beyond basic authentication, adding an extra layer of security by restricting access based on the originating IP address. We'll delve into the practical implementation using middleware, ensuring only trusted IP addresses can access designated areas of your application.
<?php
/**
* TrustedIPMiddleware.php
* Middleware to check if the request is from a trusted IP address
*
* @category Middleware
* @package App\Http\Middleware
* @version 1.0
* @since 2025-02-25
* @license https://opensource.org/licenses/MIT
*/
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\IpUtils;
class TrustedIPMiddleware
{
/**
* Array of trusted IP addresses and CIDR blocks.
* Each entry can be an IP address or a CIDR notation.
*
* @var array
*/
public $TrustedIPs = [
'127.0.0.1', // localhost
'193.195.141.0/24', // office network (example)
'80.252.125.0', // home IP (example)
'2a01:2c0::/32' // office IPv6 network (example)
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request The incoming request object.
* @param \Closure $next The next middleware in the chain.
*
* @return mixed The response from the next middleware or an abort response.
*/
public function handle($request, Closure $next)
{
// Check if the client's IP address is in the trusted list.
if (!IpUtils::checkIp($request->ip(), $this->TrustedIPs)) {
// If not trusted, abort with a 403 Forbidden response. You could also return a 404 Not Found for added security.
abort(403);
}
// If trusted, proceed to the next middleware or route.
return $next($request);
}
}
<?php
use App\Http\Middleware\TrustedIPMiddleware;
use Illuminate\Support\Facades\Route;
Route::middleware(['guest', TrustedIPMiddleware::class])->group(function () {
// Define routes that require both guest authentication and trusted IP.
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login'])->name('login.post');
// Add other authentication routes here.
});
//Other routes here, example
Route::get('/admin', function () {
return view('admin.dashboard');
})->middleware(['auth', TrustedIPMiddleware::class]);
//Remember to replace the AuthController::class with the correct path.
0 comments:
Post a Comment