限制特定 IP 存取是很常用的方法,用來限制特定的 IP 存取較敏感的 function 或API,例如後台的網頁或 API。
建立 CheckIpMiddleware
php artisan make:middleware CheckIpMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckIpMiddleware
{
//IP白名單
public $whiteIps = ['192.168.0.1', '127.0.0.1', '::1'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!in_array($request->ip(), $this->whiteIps)) {
/*
You can redirect to any error page.
*/
return response()->json([
'code' => 401,
'message' => 'your ip address is not valid.'
],401);
}
return $next($request);
}
}
註冊 Middleware
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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,
//檢查 JWT Token 及 自動更新 Token
'refresh.token' => \App\Http\Middleware\JwtRefreshToken::class,
//檢查 IP
'checkIp' => \App\Http\Middleware\CheckIpMiddleware::class,
];
修改 Route
通常檢查 IP 是最先做的事情,所以直接放在 Route 地方最適合,當然也可以放在 Controller 來拒絕存取特定的 function。
//檢查IP
Route::middleware(['checkIp'])->group(function () {
Route::post('login', [AdminLoginController::class , 'login']);
Route::post('logout', [AdminLoginController::class , 'logout']);
Route::post('refresh', [AdminLoginController::class , 'refresh']);
Route::post('me', [AdminLoginController::class , 'me']);
Route::post('list', [AdminLoginController::class , 'list']);
});