Restrict User Access From IP Address using Laravel

 

In this blog, We are going to learn how to restrict user access from IP addresses. Sometimes we don't want specific IP address should not access our website so we need this functionality. 


We will be creating middleware and blocking IP addresses from accessing URLs. This is especially useful for websites or services that contain sensitive or confidential information, or that are targeted at a specific geographic region. To implement IP address restrictions, website owners can use a variety of tools and techniques, such as firewalls, access control lists, or web application firewalls. These tools can be configured to block access to a website or service from specific IP addresses or ranges of IP addresses or to allow access only from certain trusted IP addresses.


Steps required to restrict user access from IP address:


  • Install Laravel
  • Create Middleware
  • Register Middleware
  • Use Middleware
  • Run Laravel Application


Install Laravel



This is for creating new project if you already have then you don't need this step you can move forward.


composer create-project laravel/laravel example-app

cd example-app



Create Middleware


In this step, we will create a middleware BlockIPAddressMiddleware, let's run a command:


php artisan make:middleware BlockIpAddressMiddleware


This will create middleware inside app/Http/Middleware/BlockIPAddressMiddleware.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
  
class BlockIpAddressMiddleware
{
    public $blockIps = ['whitelist-ip-1', 'whitelist-ip-2', 'whitelist-ip-3','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);
    }
}



Register Middleware



In this file, we need to register middleware on the Kernel.php file. we will call blockIP of newly created middleware. so let's update the following file.

app/Http/Kernel.php

<?php
  
namespace App\Http;
  
use Illuminate\Foundation\Http\Kernel as HttpKernel;
  
class Kernel extends HttpKernel
{
    ....
  
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'blockIP' => \App\Http\Middleware\BlockIpAddressMiddleware::class,
    ];
}



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;

   

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

    

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

    Route::resource('welcome', WelcomeController::class);

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

});



Run Laravel Application


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


php artisan serve


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





I hope you understood how to restrict user access. If you have any doubt, let me know in comments.