367 views
asked in Laravel by
Laravel 11 Black List of User IP Address using middleware

1 Answer

answered by

inchirags@gmail.com  Chirag's Laravel Tutorial https://www.chirags.in

*********************************************************************************************

Laravel 11 Black List of User IP Address using middleware

*********************************************************************************************

Here’s a step-by-step guide to implement an IP blacklist in Laravel 11 using middleware. This example will demonstrate how to deny access to specific IPs.

Step 1: Create Middleware

Run the following Artisan command to create a middleware:

php artisan make:middleware BlockBlacklistedIPs

This will create a file at app/Http/Middleware/BlockBlacklistedIPs.php.

Open the middleware file and add the following code:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class BlockBlacklistedIPs
{
    /**
     * List of blacklisted IPs.
     */
    protected $blacklistedIPs = [
        '192.168.1.10',
        '203.0.113.1',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Get the user's IP address
        $ip = $request->ip();

        // Check if the IP is blacklisted
        if (in_array($ip, $this->blacklistedIPs)) {
            return response()->json([
                'message' => 'Access denied. Your IP address is blacklisted.',
            ], 403);
        }

        return $next($request);
    }
}

Step 2: Register Middleware

Open app/Http/Kernel.php.

Add the middleware to the $routeMiddleware array:

protected $routeMiddleware = [
    // Other middleware...
    'block.blacklist' => \App\Http\Middleware\BlockBlacklistedIPs::class,
];

Step 3: Apply Middleware to Routes

Open the routes/web.php file (or routes/api.php for API routes).

Apply the middleware to specific routes or groups:

use Illuminate\Support\Facades\Route;

Route::middleware(['block.blacklist'])->group(function () {
    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('/dashboard', function () {
        return 'This is the dashboard!';
    });
});

Step 4: Test the Blacklist

Add your IP to the $blacklistedIPs array in the middleware.

Access the application using the blacklisted IP address. You should see a 403 Forbidden response:

{
    "message": "Access denied. Your IP address is blacklisted."
}

Remove your IP from the blacklist and confirm access is restored.

Step 5: Optional - Dynamic Blacklist via Configuration or Database

If you want to make the blacklist dynamic, you can load IPs from the database or a configuration file:

Example: Use a configuration file

Create a config/blacklist.php file:

return [
    '192.168.1.10',
    '203.0.113.1',
];

Modify the middleware to load IPs from the config:

protected $blacklistedIPs;
public function __construct()
{
    $this->blacklistedIPs = config('blacklist');
}

Example: Use a database

Create a blacklist_ips table using a migration:

php artisan make:migration create_blacklist_ips_table --create=blacklist_ips

Add this to the migration:

Schema::create('blacklist_ips', function (Blueprint $table) {
    $table->id();
    $table->string('ip')->unique();
    $table->timestamps();
});

Query the database in the middleware:

use Illuminate\Support\Facades\DB;
protected function getBlacklistedIPs()
{
    return DB::table('blacklist_ips')->pluck('ip')->toArray();
}
public function handle(Request $request, Closure $next)
{
    $this->blacklistedIPs = $this->getBlacklistedIPs();

    $ip = $request->ip();

    if (in_array($ip, $this->blacklistedIPs)) {
        return response()->json([
            'message' => 'Access denied. Your IP address is blacklisted.',
        ], 403);
    }

    return $next($request);
}

Testing the Dynamic Blacklist

Insert a blacklisted IP into the database:

DB::table('blacklist_ips')->insert(['ip' => '203.0.113.2']);

Try accessing the route from the blacklisted IP.

This setup provides flexibility for managing IP blacklisting in your Laravel application.

For any doubts and query, please write on YouTube video comments section.

Note : Flow the Process shown in video.

Please, Subscribe and like for more videos:

https://www.youtube.com/@chiragstutorial

Don't forget to, Follow, Like, Share &, Comment

Thanks & Regards,

Chitt Ranjan Mahto "Chirag"

_____________________________________________________________________

Note: All scripts used in this demo will be available in our website.

Link will be available in description.

#chirags 

#chiragstutorial 

#chiragslaraveltutorial

#chiragslaraveltutorials

#laraveltutorial 

#laravel11 

#laravelcourse 

#installlaravel

#laravel_tutorial 

#laravelphp

#chiragdbatutorial

#chiragsdbatutorial

#chriagstutorial

#laravel11facebooklogin

#laravelsocialitelogin

chirags, chirags tutorial, chirags laravel tutorial, chirags Laravel tutorial, Laravel tutorial, laravel11, Laravel course, install laravel, laravel_tutorial, Laravel php, chirags dba tutorial, chirags tutorial, chirag tutorial, Laravel 11 Facebook Login, Facebook Login with Laravel 11, Facebook Login with Socialite Login, 

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...