laravel:使用路由中间件限制ip地址(10.27.0)
一,相关文档:
https://learnku.com/docs/laravel/10.x/middleware/14846
二,创建middleware
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:middleware CheckIp
INFO Middleware [app/Http/Middleware/CheckIp.php] created successfully.
三,php代码
1,app/Http/Middleware/CheckIp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; use App\extend\result\Result; class CheckIp { private $ipList = [ '192.168.219.1' , '127.0.0.2' ]; /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request , Closure $next ): Response { //得到当前IP $ip = $request ->ip(); //判断是否在列表中 if (in_array( $ip , $this ->ipList)){ return Result::ErrorCode(1, "IP地址错误:" . $ip ); } return $next ( $request ); } } |
2,注册到 app/Http/Kernel.php,给它生成别名
在protected $middlewareAliases中添加我们的middleware,
给它起一个别名,如下:
protected $middlewareAliases = [
......
'checkip'=> \App\Http\Middleware\CheckIp::class,
];
如图:
3,在routes/web.php中添加对中间件的启用:
1
2
3
4
5
6
|
Route::controller(NewsController:: class )->group( function () { Route::get( '/news/home' , 'home' ); Route::get( '/news/req' , 'req' )->middleware( 'checkip' ); Route::get( '/news/res' , 'res' ); Route::get( '/news/homejson' , 'homejson' ); }); |
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/17/laravel-shi-yong-lu-you-zhong-jian-jian-xian-zhi-ip-di-zhi/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,测试效果:
路由未指定中间件:
路由被指定了中间件:
五,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0