laravel 使用中间件防止用户FQ操作
最早的时候用TP框架开发后台,防止用户FQ,通常的做法是定义一个总的控制器,然后继承此控制器
在控制器中判断是否有session,之后判断用户的登录状态
在laravel中也可以这么做,但是laravel有更吊的东西-----中间件
中间件相当于在路由访问前的过滤,根据用户的输入分发
在crsf防范中,已经用到了一个中间件,在app/http/kernal.php中定义了web中间件群组
protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ];
在路由中的使用
$router->group([ 'middleware'=>'web', 'domain' => $domain, 'namespace' => $this->backendNamespace], function ($router) { require app_path('Http/routes-backend.php'); } );
定义中间件
php artisan make:middleware AdminauthMiddleware
在app/http/middleware文件夹中会生成你需要的中间件
<?php namespace App\Http\Middleware; use Closure; class AdminauthMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { //如果未登录的不允许访问 if ( !session('user') ) { return redirect('/'); } return $next($request); } }
最后别忘了在app/http/kernal.php中定义了此中间件
/** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'adminauth'=>\App\Http\Middleware\AdminauthMiddleware::class, 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ];
在路由中使用中间件 -大功告成!
参考资料:https://laravel.com/docs/5.2/middleware
http://laravelacademy.org/post/2803.html