├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── config └── config.php └── src ├── BlacklistMiddleware.php ├── LaravelIpMiddlewareServiceProvider.php ├── Middleware.php └── WhitelistMiddleware.php /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: psr12 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-ip-middleware` will be documented in this file 4 | 5 | ## 1.8.0 - 2023-04-11 6 | 7 | - Laravel 10 support 8 | - Dropped Laravel 6 and 7 support 9 | - Dropped PHP 7 support 10 | 11 | ## 1.7.0 - 2022-07-05 12 | 13 | - Laravel 9 support 14 | 15 | ## 1.6.0 - 2021-12-17 16 | 17 | - Dropped support for PHP 7.2 18 | - Added support for PHP 8 19 | 20 | ## 1.5.0 - 2020-09-23 21 | 22 | - Added support for Laravel 8 23 | 24 | ## 1.4.0 - 2020-03-03 25 | 26 | - Added support for Laravel 7 27 | - Dropped support for Laravel 5.8 28 | 29 | ## 1.3.0 - 2020-02-12 30 | 31 | - Added support for PHP 7.4 32 | - Dropped support for PHP 7.1 33 | - PSR-12 code-style applied 34 | 35 | ## 1.2.0 - 2019-09-19 36 | 37 | - "Predefined lists" configuration added 38 | 39 | ## 1.1.0 - 2019-09-18 40 | 41 | - "Custom server parameter" configuration added 42 | 43 | ## 1.0.0 - 2019-09-18 44 | 45 | - Initial release 46 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Orkhan Ahmadov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel IP middleware 2 | 3 | [![Latest Stable Version](https://poser.pugx.org/orkhanahmadov/laravel-ip-middleware/v/stable)](https://packagist.org/packages/orkhanahmadov/laravel-ip-middleware) 4 | [![Latest Unstable Version](https://poser.pugx.org/orkhanahmadov/laravel-ip-middleware/v/unstable)](https://packagist.org/packages/orkhanahmadov/laravel-ip-middleware) 5 | [![Total Downloads](https://img.shields.io/packagist/dt/orkhanahmadov/laravel-ip-middleware)](https://packagist.org/packages/orkhanahmadov/laravel-ip-middleware) 6 | [![License](https://img.shields.io/github/license/orkhanahmadov/laravel-ip-middleware.svg)](https://github.com/orkhanahmadov/laravel-ip-middleware/blob/master/LICENSE.md) 7 | 8 | [![Build Status](https://img.shields.io/travis/orkhanahmadov/laravel-ip-middleware.svg)](https://travis-ci.org/orkhanahmadov/laravel-ip-middleware) 9 | [![Test Coverage](https://api.codeclimate.com/v1/badges/57f7522d9788782e3246/test_coverage)](https://codeclimate.com/github/orkhanahmadov/laravel-ip-middleware/test_coverage) 10 | [![Maintainability](https://api.codeclimate.com/v1/badges/57f7522d9788782e3246/maintainability)](https://codeclimate.com/github/orkhanahmadov/laravel-ip-middleware/maintainability) 11 | [![Quality Score](https://img.shields.io/scrutinizer/g/orkhanahmadov/laravel-ip-middleware.svg)](https://scrutinizer-ci.com/g/orkhanahmadov/laravel-ip-middleware) 12 | [![StyleCI](https://github.styleci.io/repos/209357635/shield?branch=master)](https://github.styleci.io/repos/209357635) 13 | 14 | Laravel middleware for whitelisting/blacklisting client IP addresses 15 | 16 | ## Requirements 17 | 18 | * PHP **8.0** or higher 19 | * Laravel **8** or higher 20 | 21 | ## Installation 22 | 23 | You can install the package via composer: 24 | 25 | ```bash 26 | composer require orkhanahmadov/laravel-ip-middleware 27 | ``` 28 | 29 | ## Usage 30 | 31 | Packages comes with `WhitelistMiddleware` and `BlacklistMiddleware` middlewares. 32 | You can register any or both of them in `$routeMiddleware` in `app/Http/Kernel.php` file: 33 | 34 | ```php 35 | protected $routeMiddleware = [ 36 | // ... 37 | 'ip_whitelist' => \Orkhanahmadov\LaravelIpMiddleware\WhitelistMiddleware::class, 38 | 'ip_blacklist' => \Orkhanahmadov\LaravelIpMiddleware\BlacklistMiddleware::class, 39 | ]; 40 | ``` 41 | 42 | Use middlewares in any of your routes and pass IP addresses. 43 | 44 | ```php 45 | Route::middleware('ip_whitelist:1.1.1.1')->get('/', 'HomeController@index'); 46 | Route::middleware('ip_blacklist:3.3.3.3')->get('/', 'PostController@index'); 47 | ``` 48 | 49 | * `ip_whitelist` middleware will block any requests where client IP not matching with whitelisted IPs. 50 | * `ip_blacklist` middleware will block requests coming from blacklisted IPs. 51 | 52 | You can also pass multiple IP addresses separated with comma: 53 | 54 | ```php 55 | Route::middleware('ip_whitelist:1.1.1.1,2.2.2.2')->get('/', 'HomeController@index'); 56 | ``` 57 | 58 | This will block all requests where client IP not matching whitelisted IP list. 59 | 60 | Package also allows setting predefine IP list in config and use them with name: 61 | 62 | ```php 63 | // config/ip-middleware.php 64 | 65 | 'predefined_lists' = [ 66 | 'my-list-1' => ['1.1.1.1', '2.2.2.2'], 67 | 'my-list-2' => ['3.3.3.3', '4.4.4.4'], 68 | ]; 69 | ``` 70 | 71 | ```php 72 | Route::middleware('ip_whitelist:my-list-1,my-list-2')->get('/', 'HomeController@index'); 73 | // you can also mix predefined list with additional IP addresses 74 | Route::middleware('ip_whitelist:my-list-1,my-list-2,5.5.5.5,6.6.6.6')->get('/', 'PostController@index'); 75 | ``` 76 | 77 | ## Configuration 78 | 79 | Run this command to publish package config file: 80 | 81 | ```bash 82 | php artisan vendor:publish --provider="Orkhanahmadov\LaravelIpMiddleware\LaravelIpMiddlewareServiceProvider" 83 | ``` 84 | 85 | `ip-middleware.php` config file contains following settings: 86 | 87 | * `ignore_environments` - Middleware ignores IP checking when application is running in listed environments. 88 | * `error_code` - HTTP code that shown when request gets rejected. 89 | * `custom_server_parameter` - Custom $_SERVER parameter to look for IP address 90 | * `predefined_lists` - Predefined IP lists 91 | 92 | ### Testing 93 | 94 | ``` bash 95 | composer test 96 | ``` 97 | 98 | ### Changelog 99 | 100 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 101 | 102 | ## Contributing 103 | 104 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 105 | 106 | ### Security 107 | 108 | If you discover any security related issues, please email ahmadov90@gmail.com instead of using the issue tracker. 109 | 110 | ## Credits 111 | 112 | - [Orkhan Ahmadov](https://github.com/orkhanahmadov) 113 | - [All Contributors](../../contributors) 114 | 115 | ## License 116 | 117 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 118 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "orkhanahmadov/laravel-ip-middleware", 3 | "description": "Laravel middleware for whitelisting/blacklisting client IP addresses", 4 | "keywords": [ 5 | "orkhanahmadov", 6 | "laravel", 7 | "middleware", 8 | "ip-filter", 9 | "ip-whitelist", 10 | "ip-blacklist", 11 | "laravel-ip-middleware" 12 | ], 13 | "homepage": "https://github.com/orkhanahmadov/laravel-ip-middleware", 14 | "license": "MIT", 15 | "type": "library", 16 | "authors": [ 17 | { 18 | "name": "Orkhan Ahmadov", 19 | "email": "ahmadov90@gmail.com", 20 | "role": "Developer" 21 | } 22 | ], 23 | "require": { 24 | "php": "^8.0", 25 | "illuminate/contracts": "^8.0|^9.0|^10.0|^11.0", 26 | "illuminate/http": "^8.0|^9.0|^10.0|^11.0", 27 | "illuminate/support": "^8.0|^9.0|^10.0|^11.0" 28 | }, 29 | "require-dev": { 30 | "orchestra/testbench": "^5.0|^6.0|^7.0", 31 | "phpunit/phpunit": "^8.0|^9.0|^10.0" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "Orkhanahmadov\\LaravelIpMiddleware\\": "src" 36 | } 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "Orkhanahmadov\\LaravelIpMiddleware\\Tests\\": "tests" 41 | } 42 | }, 43 | "scripts": { 44 | "test": "vendor/bin/phpunit", 45 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 46 | }, 47 | "extra": { 48 | "laravel": { 49 | "providers": [ 50 | "Orkhanahmadov\\LaravelIpMiddleware\\LaravelIpMiddlewareServiceProvider" 51 | ] 52 | } 53 | }, 54 | "config": { 55 | "sort-packages": true 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | [ 14 | 'local', 15 | ], 16 | 17 | /* 18 | |-------------------------------------------------------------------------- 19 | | HTTP error code 20 | |-------------------------------------------------------------------------- 21 | | 22 | | HTTP error code when request gets rejected. 23 | | Default is 403 (Forbidden). 24 | | 25 | */ 26 | 27 | 'error_code' => Illuminate\Http\Response::HTTP_FORBIDDEN, 28 | 29 | /* 30 | |-------------------------------------------------------------------------- 31 | | Custom server parameter 32 | |-------------------------------------------------------------------------- 33 | | 34 | | By default, if this configuration value is set to null middleware will use 35 | | $_SERVER['REMOTE_ADDR'] parameter to get client IP. If you want to get IP 36 | | address from different $_SERVER parameter you can set it here. 37 | | 38 | | For example, if application is behind "CloudFlare" proxy, then 'REMOTE_ADDR' 39 | | won't return real client IP, instead CloudFlare sets special 40 | | $_SERVER['HTTP_CF_CONNECTING_IP'] parameter. You need to set following 41 | | configuration to that parameter name. 42 | | 'custom_server_parameter' => 'HTTP_CF_CONNECTING_IP', 43 | | 44 | */ 45 | 46 | 'custom_server_parameter' => null, 47 | 48 | /* 49 | |-------------------------------------------------------------------------- 50 | | Predefined IP lists 51 | |-------------------------------------------------------------------------- 52 | | 53 | | Here you can predefine IP list that middleware can use with list key name. 54 | | You can use array list or comma separated string to set IP addresses. 55 | | Or you can use environment key. 56 | | 57 | */ 58 | 59 | 'predefined_lists' => [ 60 | // 'list-1' => ['1.1.1.1', '2.2.2.2'], 61 | // 'list-2' => '3.3.3.3,4.4.4.4', 62 | // 'list-3' => env('IP_WHITELIST'), // in .env file: IP_WHITELIST=5.5.5.5,6.6.6.6,7.7.7.7 63 | ], 64 | ]; 65 | -------------------------------------------------------------------------------- /src/BlacklistMiddleware.php: -------------------------------------------------------------------------------- 1 | shouldCheck() && in_array($this->clientIp($request), $this->ipList($blacklist))) { 22 | $this->abort(); 23 | } 24 | 25 | return $next($request); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/LaravelIpMiddlewareServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 18 | $this->publishes([ 19 | __DIR__ . '/../config/config.php' => config_path('ip-middleware.php'), 20 | ], 'config'); 21 | } 22 | } 23 | 24 | /** 25 | * Register the application services. 26 | */ 27 | public function register(): void 28 | { 29 | $this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'ip-middleware'); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Middleware.php: -------------------------------------------------------------------------------- 1 | application = $application; 30 | $this->config = $config; 31 | } 32 | 33 | /** 34 | * Returns client IP address. 35 | * 36 | * @param Request $request 37 | * @return string 38 | */ 39 | protected function clientIp($request): string 40 | { 41 | return $this->config->get('ip-middleware.custom_server_parameter') 42 | ? $request->server->get($this->config->get('ip-middleware.custom_server_parameter')) 43 | : $request->ip(); 44 | } 45 | 46 | /** 47 | * Return result if middleware should IP check. 48 | * 49 | * @return bool 50 | */ 51 | protected function shouldCheck(): bool 52 | { 53 | return ! $this->application->environment($this->config->get('ip-middleware.ignore_environments')); 54 | } 55 | 56 | /** 57 | * Returns IP address list parsed from original middleware parameter. 58 | * 59 | * @param array $list 60 | * 61 | * @return array 62 | */ 63 | protected function ipList(array $list): array 64 | { 65 | $predefinedLists = $this->config->get('ip-middleware.predefined_lists'); 66 | 67 | $finalList = []; 68 | foreach (Arr::flatten($list) as $item) { 69 | if (isset($predefinedLists[$item])) { 70 | $finalList[] = $this->parsePredefinedListItem($predefinedLists[$item]); 71 | } else { 72 | $finalList[] = $item; 73 | } 74 | } 75 | 76 | return Arr::flatten($finalList); 77 | } 78 | 79 | /** 80 | * @param array|string $item 81 | * 82 | * @return array 83 | */ 84 | private function parsePredefinedListItem($item): array 85 | { 86 | if (is_array($item)) { 87 | return $item; 88 | } 89 | 90 | return explode(',', $item); 91 | } 92 | 93 | /** 94 | * Aborts application with configured error code. 95 | */ 96 | protected function abort() 97 | { 98 | return $this->application->abort( 99 | $this->config->get('ip-middleware.error_code') 100 | ); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/WhitelistMiddleware.php: -------------------------------------------------------------------------------- 1 | shouldCheck() && ! in_array($this->clientIp($request), $this->ipList($whitelist))) { 22 | $this->abort(); 23 | } 24 | 25 | return $next($request); 26 | } 27 | } 28 | --------------------------------------------------------------------------------