olssonm / blockip
在 Laravel 5 中阻止来自指定 IP 的请求。
v6.0.0
2021-02-17 15:44 UTC
Requires
- php: >=7.3|^8.0
- illuminate/support: ^8.0
Requires (Dev)
- orchestra/testbench: ^6.0
README
在 Laravel 中快速、轻松地阻止来自指定 IP 的请求。高度可定制。
版本兼容性
安装
通过 Composer
$ composer require olssonm/blockip
将服务提供者添加到 config/app.php
中的 providers 数组(在较新的 Laravel 版本中也可自动检测)。
<?php 'providers' => [ Olssonm\Blockip\BlockipServiceProvider::class ]
使用
此包设置了 blockip
-中间件以在您的应用程序中使用。所有使用中间件的路由都受到不受欢迎的请求的保护。
在组中使用
<?php Route::group(['middleware' => 'blockip'], function() { Route::get('/', ['as' => 'start', 'uses' => 'StartController@index']); Route::get('/page', ['as' => 'page', 'uses' => 'StartController@page']); });
单个路由
<?php Route::get('/', [ 'as' => 'start', 'uses' => 'StartController@index', 'middleware' => 'blockip' ]);
配置
运行命令 $ php artisan vendor:publish --provider="Olssonm\Blockip\BlockipServiceProvider"
以发布包配置。在 config/blockip.php
中您可以编辑设置
<?php return [ // IPs to block 'ips' => [ '37.123.187.245', // an example of a single IP '23.20.0.0/14' // an example of an IP-range with CIDR-notation ], // Message for blocked requests 'error_message' => '401 Unauthorized.', // Uncomment to use a view instead of plaintext message // 'error_view' => 'blockip::default', // Environments where the middleware is active 'envs' => [ 'testing', 'development', 'production' ], // Main handler for the getIp(), getIpsToBlock() and getError-methods(). // Check the documentation on how to customize this to your liking. 'handler' => Olssonm\Blockip\Handlers\BlockipHandler::class, ];
这里的内容基本上都是自我解释的,但由于 blockip 处理器可定制,您可以更改中间件的各个方面。
如果您想编写自己的处理器,应实现 Olssonm\Blockip\Handlers\BaseHandler
-接口,如下所示
<?php use Olssonm\Blockip\Handlers\BaseHandler; class MyHandler implements BaseHandler { /** * @return string */ public function getIp() { // Method to retrieve the request IP } /** * @return array */ public function getIpsToBlock() { // Method to set what IPs to be blocked } /** * @return response */ public function getError() { // Method to set the response } }
使用此系统,您有权限例如使您的 getIpsToBlock()
-方法检查来自 API 的 IP,您的 getError()
返回 JSON 响应等等。
注意:默认处理器已经检查在 Cloudflare CDN 使用时特殊的 HTTP_CF_CONNECTING_IP
-头。
测试
$ composer test
或
$ phpunit
Laravel 在运行测试时始终在 "测试" 环境中运行。确保在 blockip.php
中的 envs
-数组中设置了 testing
。
许可
MIT 许可证 (MIT)。有关更多信息,请参阅许可文件。
© 2021 Marcus Olsson。