Restrict User With IP in Laravel V10
We can easily restrict users with Ips in any laravel application. Restriction means you want to make your web application for a few users whose IPs y...
Gurpreet Kait
Author
We can easily restrict users with Ips in any laravel application. Restriction means you want to make your web application for a few users whose IPs y...
Gurpreet Kait
Author
We can easily restrict users with Ips in any laravel application. Restriction means you want to make your web application for a few users whose IPs you have added to the system. Then it's very easy.
We need to make a middleware that will verify the IP addresses and redirect the user accordingly.
I assume that you know how to create a project in Laravel if you don't please look at the documentation.
//create project
composer create-project laravel/laravel app
php artisan make:middleware AllowOnlySpecificIPsMiddleware
Then add this code to the middleware PHP file.
<?php
namespace App\Http\Middleware;
use App\Models\AllowedIp;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class AllowOnlySpecificIPsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle($request, Closure $next)
{
$allowedIPs = AllowedIp::all()->pluck('ip_address')->toArray();
$clientIP = $request->ip();
$clientIP = $request->header('CF-Connecting-IP', $request->ip());
Log::info("client ip $clientIP " . json_encode($request));
if (in_array($clientIP, $allowedIPs)) {
return $next($request);
}
abort(403, 'Unauthorized. Your IP address is not allowed');
}
}
Explanation: Let me explain what we just did in the above code. We table called allowed_ip
which has been represented by AllowedIp
The model that we are using in the code AllowedIp::all()->pluck('ip_address')->toArray();
Now we are getting the client IP from $request->IP()
variable. After comparing if the IP exists in the table we can return the request else we will return a 403 (Reequest is unauthorized) error.
Now you can use this middleware in your routes.
I hope this article helps you. I just wrote this article to the point you may need to register this to use in routes etc. Thanks for reading.