How to Restrict User Access from IP Address in Laravel 11?

10-May-2024

.

Admin

How to Restrict User Access from IP Address in Laravel 11?

Hi, Dev

In this concise guide, we'll delve into the process of restricting user access based on IP addresses within a Laravel 11 application. We'll accomplish this by crafting middleware designed to thwart user access by their IP addresses.

At times, it becomes necessary to prevent certain IP addresses from accessing our website. In this guide, I'll demonstrate how to develop middleware that effectively blocks unwanted IP addresses from accessing specific URLs. By implementing this IP address-based restriction, website administrators can ensure that only authorized individuals gain entry to their site or service. This feature proves invaluable for platforms housing sensitive data or catering to specific geographical demographics.

Enforcing IP address restrictions involves employing an array of tools and techniques such as firewalls, access control lists, or web application firewalls. These resources can be configured to either block access from designated IP addresses or ranges, or conversely, permit access solely from trusted IPs.

In this tutorial example, we will create one middleware called "BlockIpMiddleware" and we will use that middleware on every secure API and URL. So the middleware will check the IP address against a given blacklist of IPs. Let's see the simple steps:

Step for Laravel 11 Black List of User IP Address Example


Step 1: Install Laravel 11

Step 2: Create Middleware

Step 3: Register Middleware

Step 4: Use Middleware

Run Laravel App

Step 1: Install Laravel 11

First of all, we need to get a fresh Laravel 11 version application using the command below because we are starting from scratch. So, open your terminal or command prompt and run the command below:

composer create-project laravel/laravel example-app

In this step, open the terminal and run the command below to create the BlockIpMiddleware middleware file. So, let's run the command below:

Step 2: Create Middleware

php artisan make:middleware BlockIpMiddleware

Now, it's created a new BlockIpMiddleware.php file. You have to add blocked IPs to the $blockIps array list. Let's update the following code in this file.

app/Http/Middleware/BlockIpMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

use Symfony\Component\HttpFoundation\Response;

class BlockIpMiddleware

{

public $blockIps = ['whitelist-ip-1', 'whitelist-ip-2', '127.0.0.1'];

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next

* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse

*/

public function handle(Request $request, Closure $next): Response

{

if (in_array($request->ip(), $this->blockIps)) {

abort(403, "You are restricted to access the site.");

}

return $next($request);

}

}

Step 3: Register Middleware

In this file, we need to register middleware in the app.php file. We will call the blockIP middleware newly created. So let's update the following file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;

use Illuminate\Foundation\Configuration\Exceptions;

use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))

->withRouting(

web: __DIR__.'/../routes/web.php',

commands: __DIR__.'/../routes/console.php',

health: '/up',

)

->withMiddleware(function (Middleware $middleware) {

$middleware->alias([

'blockIP' => \App\Http\Middleware\BlockIpMiddleware::class,

]);

})

->withExceptions(function (Exceptions $exceptions) {

//

})->create();

Step 4: Use Middleware

In this step, we will create one route and show you how to use middleware in the route file. So let's open your route file and update the following code:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\RSSFeedController;

use App\Http\Controllers\UserController;

Route::middleware(['blockIP'])->group(function () {

Route::resource('users', UserController::class);

Route::resource('rss', RSSFeedController::class);

});

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/users

You will find following layout:

laravel-11-ip-address

I hope it can help you...

#Laravel 11