前言
上篇講到如何驗證request傳入的參數,但如果有個參數,大家必須要有它才能進一步使用呢?例如使用者資訊的API需要登入後取得的token、新增紀錄的API也要有token才能確保是哪位使用者在新增紀錄...
這時候可以使用 Middleware (中介層)來達成此目的,先做一次過濾後再讓request進controller。
php artisan make:middleware checkToken
新增完成後,可在「 app/Http/Middleware 」路徑之下找到新稱的檔案
public function handle($request, Closure $next)
{
//先確認token是否存在
$user = User::where('remember_token', '=', $request->remember_token)->first();
if ($user) {
return $next($request);
}else{
return response()->json(['message' => 'User Token not found 2 !'], 404);
}
}
class Kernel extends HttpKernel{
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'checkToken' => \App\Http\Middleware\checkToken::class,
];
Route::middleware(['checkToken'])->group(function () {
Route::post('info', 'Auth\LoginController@userInfo');
Route::post('logout', 'Auth\LoginController@logoutAPI');
});
把要事前檢驗的 api 放到 group裡頭。
如果有多個,可以一個一個列出
Route::middleware(['first', 'second'])->group(function () {
});
或是寫在 Kernel的 middlewareGroups
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
],
];
//直接列出 middlewareGroups 的 name
Route::group(['middleware' => ['web']], function () {
//});
可以透過 php artisan route:list
確認哪API受哪個middleware設定。
middleware 除了可以寫在router之外,也可以寫在controller。
參考資料
https://laravel.com/docs/7.x/middleware#introduction
https://docs.laravel-dojo.com/laravel/5.5/middleware
https://ithelp.ithome.com.tw/articles/10208371
https://ithelp.ithome.com.tw/articles/10223325